IOS 创建渐变图层

时间:2021-01-25 22:04:28
代码如下
typedef enum {
GradientLayerKindLeftRight = ,
GradientLayerKindUpDown,
GradientLayerKindLBRT,//左下-右上
GradientLayerKindLTRB //左上-右下
}GradientLayerKind;
//--------------------------------------------------------------
// 创建矩形渐变图层
//
// @param frame 渐变图层的frame
// @param startColor 起始颜色(设置起止颜色的时候可以设置颜色的透明度达到透明度渐变的效果)
// @param endColor 终止颜色
// @param kind 渐变类型
// GradientLayerKindLeftRight = 1,//左-右
// GradientLayerKindUpDown, //上-下
// GradientLayerKindLBRT, //左下-右上
// GradientLayerKindLTRB //左上-右下
// @return 渐变色layer
//----------------------------------------------------------
- (CALayer*)ct_getGradientLayerWithFrame:(CGRect)frame StartColor:(UIColor *)startColor endColor:(UIColor*)endColor andKind:(GradientLayerKind)kind{
//渐变图层
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = frame;
[gradientLayer setColors:[NSArray arrayWithObjects:(id)[startColor CGColor],(id)[endColor CGColor], nil]]; if (kind == GradientLayerKindUpDown) {
[gradientLayer setLocations:@[@,@]]; [gradientLayer setStartPoint:CGPointMake(0.5, )]; [gradientLayer setEndPoint:CGPointMake(0.5, )];
}else if (kind == GradientLayerKindLeftRight){
[gradientLayer setLocations:@[@,@]]; [gradientLayer setStartPoint:CGPointMake(, 0.5)]; [gradientLayer setEndPoint:CGPointMake(, 0.5)];
}else if (kind == GradientLayerKindLTRB){
[gradientLayer setLocations:@[@,@]]; [gradientLayer setStartPoint:CGPointMake(, )]; [gradientLayer setEndPoint:CGPointMake(, )];
}else if (kind == GradientLayerKindLBRT){
[gradientLayer setLocations:@[@,@]]; [gradientLayer setStartPoint:CGPointMake(, )]; [gradientLayer setEndPoint:CGPointMake(, )];
} return gradientLayer; }
使用:viewcontroller的viewdidload中
for (int i = ; i < ; i++) {
NSInteger hang = i%,lie=i/;
CGFloat w=self.view.frame.size.width/2.0,h=(self.view.frame.size.height-)/2.0;
CGRect frame = CGRectMake(hang*w, lie*h, w, h);
[self.view.layer addSublayer:[self ct_getGradientLayerWithFrame:frame StartColor:[self rgb: g: b: a:0.9] endColor:[self rgb: g: b: a:0.1] andKind:i+]]; }
设置颜色方法:
-(UIColor*)rgb:(NSInteger)r g:(NSInteger)g b:(NSInteger)b a:(CGFloat)alpha{
return [UIColor colorWithRed:r%/256.0 green:g%/256.0 blue:b%/256.0 alpha:alpha]; }
效果图如图所示:(可以发现图层下的label和按钮都可以显示,并且按钮的点击事件正常响应)

IOS 创建渐变图层