CAGradientLayer实现渐变

CAGradientLayer是CALayer的一个子类,用来生成渐变色的Layer。
CAGradientLayer有5个属性:

@property(nullable, copy) NSArray *colors; // CGColorRef数组,用来定义渐变节点颜色
@property(nullable, copy) NSArray<NSNumber *> *locations; // 存储每个渐变节点位置
@property CGPoint startPoint; // 渐变色的起始点
@property CGPoint endPoint; // 渐变色的结束点,和起始点共同能够成渐变方向
@property(copy) NSString *type; // 没什么意义,只能设置为axial

CAGradientLayer具体使用方法如下:

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.startPoint = CGPointMake(0, 0);
gradient.endPoint = CGPointMake(1, 1);
gradient.locations = @[@0.3, @0.5, @0.6];
gradient.colors = [NSArray arrayWithObjects:
                   (id)[UIColor redColor].CGColor,
                   (id)[UIColor greenColor].CGColor,
                   (id)[UIColor blueColor].CGColor,
                   nil];

最后把gradientadd到view.layer上就可以了,最终效果是这样的:

渐变色

但是这种方式用在UIButton上的时候就有点美中不足了,因为我们都希望一个Button在点击的时候会有高亮的效果,但在Button的Layer上又添加了一层gradient,就会导致点击的时候颜色无法改变,因此我们需要将CAGradientLayer转为UIImage,并通过setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state方法设置上去就可以解决了。

通过CALayer创建UIImage:

- (UIImage *)imageFromLayer:(CALayer *)layer {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0);
    
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return outputImage;
}

设置完之后按中时的效果:


高亮
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容