给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
网友评论