渐变色

按钮渐变背景

920 发布: 2019/8/20 00:51 本文总阅读量

知识扩展

iOS渐变方案

利用UIImage扩展实现渐变背景

.h
@interface UIImage (RKImgCategory)

typedef NS_ENUM(NSUInteger, RKGradientType) {
    RKGradientTypeTopToBottom = 0,//从上到下
    RKGradientTypeLeftToRight = 1,//从左到右
    RKGradientTypeUpleftToLowright = 2,//左上到右下
    RKGradientTypeUprightToLowleft = 3,//右上到左下
};
/**  设置图片的渐变色(颜色->图片)
@param colors 渐变颜色数组  @param gradientType 渐变样式  @param imgSize 图片大小  @return 颜色->图片  */
+ (UIImage *)rk_gradientColorImageFromColors:(NSArray*)colors gradientType:(RKGradientType)gradientType imgSize:(CGSize)imgSize;

@end
.m
#import "UIImage+RKImgCategory.h"

@implementation UIImage (RKImgCategory)

+ (UIImage *)rk_gradientColorImageFromColors:(NSArray*)colors gradientType:(RKGradientType)gradientType imgSize:(CGSize)imgSize {
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    switch (gradientType) {
        case RKGradientTypeTopToBottom:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(0.0, imgSize.height);
            break;
        case RKGradientTypeLeftToRight:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(imgSize.width, 0.0);
            break;
        case RKGradientTypeUpleftToLowright:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(imgSize.width, imgSize.height);
            break;
        case RKGradientTypeUprightToLowleft:
            start = CGPointMake(imgSize.width, 0.0);
            end = CGPointMake(0.0, imgSize.height);
            break;
        default:
            break;
    }
    CGContextDrawLinearGradient(context, gradient, start, end,kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

@end