IOS 创建渐变图层

代码如下
typedef enum {
    GradientLayerKindLeftRight = 2000,
    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:@[@0,@1]];
        
        [gradientLayer setStartPoint:CGPointMake(0.5, 0)];
        
        [gradientLayer setEndPoint:CGPointMake(0.5, 1)];
    }else if (kind == GradientLayerKindLeftRight){
        [gradientLayer setLocations:@[@0,@1]];
        
        [gradientLayer setStartPoint:CGPointMake(0, 0.5)];
        
        [gradientLayer setEndPoint:CGPointMake(1, 0.5)];
    }else if (kind == GradientLayerKindLTRB){
        [gradientLayer setLocations:@[@0,@1]];
        
        [gradientLayer setStartPoint:CGPointMake(0, 0)];
        
        [gradientLayer setEndPoint:CGPointMake(1, 1)];
    }else if (kind == GradientLayerKindLBRT){
        [gradientLayer setLocations:@[@0,@1]];
        
        [gradientLayer setStartPoint:CGPointMake(0, 1)];
        
        [gradientLayer setEndPoint:CGPointMake(1, 0)];
    }
    
    return gradientLayer;
 
}
使用:viewcontroller的viewdidload中
    for (int i = 0; i < 4; i++) {
        NSInteger hang = i%2,lie=i/2;
        CGFloat w=self.view.frame.size.width/2.0,h=(self.view.frame.size.height-64)/2.0;
        CGRect frame = CGRectMake(hang*w, lie*h, w, h);
        [self.view.layer addSublayer:[self ct_getGradientLayerWithFrame:frame StartColor:[self rgb:0 g:0 b:0 a:0.9] endColor:[self rgb:255 g:255 b:255 a:0.1] andKind:i+2000]];
 
    }
设置颜色方法:
-(UIColor*)rgb:(NSInteger)r g:(NSInteger)g b:(NSInteger)b a:(CGFloat)alpha{
    return [UIColor colorWithRed:r%256/256.0 green:g%256/256.0 blue:b%256/256.0 alpha:alpha];
 
}
效果图如图所示:(可以发现图层下的label和按钮都可以显示,并且按钮的点击事件正常响应)

posted @ 2016-07-19 17:02  熹微_念  阅读(351)  评论(0编辑  收藏  举报