CAGradientLayer實現漸變

CAGradientLayer是CALayer的一個子類,用來生成漸變色的Layer。
CAGradientLayer有5個屬性:

@property(nullable, copy) NSArray *colors; // CGColorRef數組,用來定義漸變節(jié)點顏色
@property(nullable, copy) NSArray<NSNumber *> *locations; // 存儲每個漸變節(jié)點位置
@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創(chuàng)建UIImage:

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

設置完之后按中時的效果:


高亮
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容