漸變色
給View添加漸變色的方法有多種,這里采用CAGradientLayer
來實現漸變效果。CAGradientLayer
的好處在于繪制使用了硬件加速。
CAGradientLayer在背景色上繪制顏色漸變,填充圖層的形狀(包括圓角)。
一個簡單的例子:
UIView *colorView = [[UIView alloc] init];
[colorView setFrame:CGRectMake(20, 160,
self.view.frame.size.width - 40, self.view.frame.size.height - 320)];
[self.view addSubview:colorView];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = colorView.bounds;
gradient.colors = [NSArray arrayWithObjects:
(id)[UIColor colorWithRed:0 green:143/255.0 blue:234/255.0 alpha:1.0].CGColor,
(id)[UIColor colorWithRed:0 green:173/255.0 blue:234/255.0 alpha:1.0].CGColor,
(id)[UIColor whiteColor].CGColor, nil];
[colorView.layer addSublayer:gradient];
效果如下:
藍色漸變
CAGradientLayer
屬于QuartzCore
,QuartzCore
提供動畫和動畫顯示層次功能的應用程序。
CAGradientLayer
有5個屬性:
-
colors: An array of CGColorRef
objects defining the color of each gradient stop. Animatable. - locations: An optional array of NSNumber objects defining the location of each gradient stop. Animatable.
- endPoint: The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
- startPoint: The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
- type: Style of gradient drawn by the layer.
colors
中設置漸變的顏色;locations
中設置顏色的范圍,大小在[0, 1]內,默認為平均;startPoint
和endPoint
設置漸變的起始位置,范圍在[0, 1]內;type
設置漸變樣式,目前僅支持線性漸變(kCAGradientLayerAxial)。
對角線漸變,漸變范圍0.0,0.2,0.5,一定要確保locations
數組和colors數組大小相同,否則會得到一個空白的漸變。
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = colorView.bounds;
gradient.colors = [NSArray arrayWithObjects:
(id)[UIColor magentaColor].CGColor,
(id)[UIColor cyanColor].CGColor,
(id)[UIColor greenColor].CGColor, nil];
gradient.startPoint = CGPointMake(0, 0);
gradient.endPoint = CGPointMake(1, 1);
gradient.locations = @[@0.0, @0.2, @0.5];
[colorView.layer addSublayer:gradient];
效果如下:
對角線漸變
參考:
CAGradientLayer