效果如下:
实现代码如下:
.H
#import <UIKit/UIKit.h> /** 渐变方式 - IHGradientChangeDirectionLevel: 水平渐变 - IHGradientChangeDirectionVertical: 竖直渐变 - IHGradientChangeDirectionUpwardDiagonalLine: 向下对角线渐变 - IHGradientChangeDirectionDownDiagonalLine: 向上对角线渐变 */ typedef NS_ENUM(NSInteger, IHGradientChangeDirection) { IHGradientChangeDirectionLevel, IHGradientChangeDirectionVertical, IHGradientChangeDirectionUpwardDiagonalLine, IHGradientChangeDirectionDownDiagonalLine, }; @interface UIColor (IHGradientChange) /** 创建渐变颜色 @param size 渐变的size @param direction 渐变方式 @param startcolor 开始颜色 @param endColor 结束颜色 @return 创建的渐变颜色 */ + (instancetype)bm_colorGradientChangeWithSize:(CGSize)size direction:(IHGradientChangeDirection)direction startColor:(UIColor *)startcolor endColor:(UIColor *)endColor; // 其他曲线渐变暂不考虑 @end
.M:
#import "UIColor+IHGradientChange.h" @implementation UIColor (IHGradientChange) + (instancetype)bm_colorGradientChangeWithSize:(CGSize)size direction:(IHGradientChangeDirection)direction startColor:(UIColor *)startcolor endColor:(UIColor *)endColor { if (CGSizeEqualToSize(size, CGSizeZero) || !startcolor || !endColor) { return nil; } CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = CGRectMake(0, 0, size.width, size.height); CGPoint startPoint = CGPointZero; if (direction == IHGradientChangeDirectionDownDiagonalLine) { startPoint = CGPointMake(0.0, 1.0); } gradientLayer.startPoint = startPoint; CGPoint endPoint = CGPointZero; switch (direction) { case IHGradientChangeDirectionLevel: endPoint = CGPointMake(1.0, 0.0); break; case IHGradientChangeDirectionVertical: endPoint = CGPointMake(0.0, 1.0); break; case IHGradientChangeDirectionUpwardDiagonalLine: endPoint = CGPointMake(1.0, 1.0); break; case IHGradientChangeDirectionDownDiagonalLine: endPoint = CGPointMake(1.0, 0.0); break; default: break; } gradientLayer.endPoint = endPoint; gradientLayer.colors = @[(__bridge id)startcolor.CGColor, (__bridge id)endColor.CGColor]; UIGraphicsBeginImageContext(size); [gradientLayer renderInContext:UIGraphicsGetCurrentContext()]; UIImage*image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return [UIColor colorWithPatternImage:image]; } @end