首页 > 代码库 > iOS 之渐变颜色
iOS 之渐变颜色
效果如下:
实现代码如下:
.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
github源码
我的blog
iOS 之渐变颜色
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。