效果如下:
實現代碼如下:
.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