iOS顏色漸變之CAGradientLayer

簡介

CAGradientLayerCALayer的一個子類,是一個可以設置漸變色的圖層,我們所設置的漸變色會覆蓋原有layer背景色,并且漸變色會填充整個layer形狀(包括圓角)。

創建

和一般的CALayer的創建方式相同

CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(0, 100, self.view.frame.size.width, 200);
[self.view.layer addSublayer:gradientLayer];

屬性

  • 漸變類型
@property(copy) NSString *type;
/* The kind of gradient that will be drawn. Currently the only allowed
 * value is `axial' (the default value). */

目前(iOS10.3)蘋果所提供的漸變類型只有一種:

CA_EXTERN NSString * const kCAGradientLayerAxial CA_AVAILABLE_STARTING (10.6, 3.0, 9.0, 2.0); 

這種類型稱為軸向梯度(也稱為線性梯度),就是沿著兩個確定端點之間的軸線變化,所有與軸垂直的點都有相同的顏色值。

  • 漸變軸線的起點和終點
@property CGPoint startPoint;
@property CGPoint endPoint;
/* The start and end points of the gradient when drawn into the layer's
 * coordinate space. The start point corresponds to the first gradient
 * stop, the end point to the last gradient stop. Both points are
 * defined in a unit coordinate space that is then mapped to the
 * layer's bounds rectangle when drawn. (I.e. [0,0] is the bottom-left
 * corner of the layer, [1,1] is the top-right corner.) The default values
 * are [.5,0] and [.5,1] respectively. Both are animatable. */
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint   = CGPointMake(1, 1);

直接上圖吧:


startPointendPoint分別代表了漸變顏色的起點和終點,在layer的左上角值為(0,0),右下角值為(1,1)
我們可以通過調整起點和終點的位置來調整漸變軸線的方向。

調整一下起點和終點的位置,再來看一下效果

gradientLayer.startPoint = CGPointMake(0, 0.5);
gradientLayer.endPoint   = CGPointMake(1, 0.5);
  • 漸變色組
@property(nullable, copy) NSArray *colors;
/* The array of CGColorRef objects defining the color of each gradient
 * stop. Defaults to nil. Animatable. */

制作一個顏色的漸變至少需要2個顏色,一個起始顏色和一個終止顏色。當然顏色的漸變也有可能在多個顏色值之間變化,這時我們就需要設置多個顏色值。
那么這些顏色值得設置是怎么實現的呢?這時就需要用到我們的colors屬性來設置。
上面看到的效果的colors屬性設置是這樣的:

gradientLayer.colors = @[(id)[UIColor whiteColor].CGColor,(id)[UIColor blueColor].CGColor];

?? 注意:這里要說一下的就是colors屬性所接收的數組中的元素類型是CGColorRef

下面我們設置多個顏色值,來看一下效果是怎樣的

gradientLayer.colors = @[(id)[UIColor whiteColor].CGColor,(id)[UIColor redColor].CGColor,(id)[UIColor blueColor].CGColor,];
  • 顏色值位置
@property(nullable, copy) NSArray<NSNumber *> *locations;
/* An optional array of NSNumber objects defining the location of each
 * gradient stop as a value in the range [0,1]. The values must be
 * monotonically increasing. If a nil array is given, the stops are
 * assumed to spread uniformly across the [0,1] range. When rendered,
 * the colors are mapped to the output colorspace before being
 * interpolated. Defaults to nil. Animatable. */

上面我們所看到的漸變色,顏色與顏色之間的漸變區間都是平均等分的


我們可以通過locations屬性,設置各色值在軸線上的位置:

gradientLayer.locations = @[@0.0, @0.75, @1.0];


?? 注意:locations屬性中的值要與colors屬性中的值一一對應。
而且locations屬性是支持動畫效果的,可以看出CAGradientLayer是可以實現很多炫酷的動畫效果的。

版權聲明:出自MajorLMJ技術博客的原創作品 ,轉載時必須注明出處及相應鏈接!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容