iOS之view的背景绘制渐变色、文字渐变

参考:http://www.jianshu.com/p/3e0e25fd9b85

CAGradientLayer类

CAGradientLayer类在苹果API文档中其说明为:CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角).
其继承关系图如下:


DEB0F788-271F-40BB-9D67-43CD63876376.png

CAGradientLayer继承CAlayer,设置其属性都会有GPU绘制运算

用到的属性有:

  1. colors 渐变的颜色
  2. locations 颜色变化位置的取值范围
  3. startPoint 颜色渐变的起始位置:取值范围在(0,0)~(1,1)之间
  4. endPoint 颜色渐变的终点位置,取值范围也是在(0,0)~(1,1)之间
    补充下:startPoint & endPoint设置为(0,0)(1.0,0)代表水平方向渐变,(0,0)(0,1.0)代表竖直方向渐变

-(void)graint{

    CAGradientLayer *layer=[CAGradientLayerlayer];

    layer.frame=self.creditCardNolabl.frame;

    [layer setColors:@[(id)[UIColorredColor].CGColor, (id)[UIColorblueColor].CGColor]];

    [self.creditCardNolabl.layeraddSublayer:layer];

    //颜色上下渐变

    [layer setStartPoint:CGPointMake(0, 0)];

    [layer setEndPoint:CGPointMake(0, 1)];


}



 //为透明度设置渐变效果

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];

    UIColor *colorOne = [UIColor colorWithRed:(216/255.0)  green:(0/255.0)  blue:(18/255.0)  alpha:1.0];

    UIColor *colorTwo = [UIColor colorWithRed:(216/255.0)  green:(0/255.0)  blue:(18/255.0)  alpha:0.0];

    NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];

    CAGradientLayer *gradient = [CAGradientLayer layer];

    view.layer.masksToBounds = YES;

    //设置开始和结束位置(设置渐变的方向)

    gradient.startPoint = CGPointMake(0, 0);

    gradient.endPoint = CGPointMake(1, 0);

    gradient.colors = colors;

    gradient.frame = CGRectMake(0, 0, 40, 40);

    [view.layerinsertSublayer:gradientatIndex:0];

    [self.view addSubview:view];


=====

-(UIImage *)drawcont{

    UIGraphicsBeginImageContext(self.creditCardNolabl.frame.size);

 CGContextRef context =UIGraphicsGetCurrentContext();

    

    CGContextClip(context);

    CGColorSpaceRef rgb =CGColorSpaceCreateDeviceRGB();

    CGFloat colors[] =

    {

        204.0 / 255.0, 224.0 / 255.0, 244.0 / 255.0, 1.00,

        29.0 / 255.0, 156.0 / 255.0, 215.0 / 255.0, 1.00,

        0.0 / 255.0,  50.0 / 255.0, 126.0 / 255.0, 1.00,

    };

    CGGradientRef gradient =CGGradientCreateWithColorComponents

    (rgb, colors, NULL,sizeof(colors)/(sizeof(colors[0])*4));

    CGColorSpaceRelease(rgb);

    CGContextDrawLinearGradient(context, gradient,CGPointMake

                                (0.0,0.0) ,CGPointMake(0.0,self.frame.size.height),

                                kCGGradientDrawsBeforeStartLocation);

    UIImage *theImage =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return theImage;

}


===========

1-> 线性渐变


- (void)drawLinearGradient:(CGContextRef)context

path:(CGPathRef)path

startColor:(CGColorRef)startColor

                  endColor:(CGColorRef)endColor View:(UIView *)v

    {

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGFloat locations[] = { 0.0,1.0 };//这个是两种颜色的位置

        //        CGFloat locations[] = { 0.0, 0.5,1.0 };//这个是三种颜色的位置

        

        //      NSArray *colors = @[(__bridge id)startColor,(__bridge id)[UIColor blueColor].CGColor,(__bridge id)endColor];//渐变颜色的种类,要和上边的locations对应;


         NSArray *colors = @[(__bridge id)startColor,(__bridge id)endColor];

        

        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);

        

        

//        CGRect pathRect = CGPathGetBoundingBox(path);

        

        //具体方向可根据需求修改

//        CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMinY(pathRect));

//        CGPoint endPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMaxY(pathRect));

        CGPoint startPoint = CGPointMake(20,v.frame.size.height);

        CGPoint endPoint = CGPointMake(20,0);

        CGContextSaveGState(context);

        CGContextAddPath(context, path);

        CGContextClip(context);

        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

        CGContextRestoreGState(context);

        

        CGGradientRelease(gradient);

        CGColorSpaceRelease(colorSpace);

    }

    

   


-(UIImage *)getImageWithView:(UIView *)v{


    //创建CGContextRef

    UIGraphicsBeginImageContext(self.bounds.size);

    CGContextRef gc = UIGraphicsGetCurrentContext();

    

    //创建CGMutablePathRef

    CGMutablePathRef path = CGPathCreateMutable();

    

    //绘制Path

    CGPathMoveToPoint(path, NULL, 0,0);

    CGPathAddLineToPoint(path, NULL, v.bounds.size.width,0);

    CGPathAddLineToPoint(path, NULL, v.bounds.size.width,v.bounds.size.height);

    CGPathAddLineToPoint(path, NULL, 0,v.bounds.size.height);

    CGPathCloseSubpath(path);

    

    //绘制渐变

    UIColor *starColor=[UIColor colorWithRed:127.0/255 green:175.0/255 blue:174.0/255 alpha:1.0];

    UIColor *endColor=[UIColor colorWithRed:204.0/255 green:233.0/255 blue:233.0/255 alpha:1.0];

    [self drawLinearGradient:gc path:path startColor:starColor.CGColor endColor:endColor.CGColor View:v];

    

    //注意释放CGMutablePathRef

    CGPathRelease(path);

    

    //Context中获取图像,并显示在界面上

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;

}


2-> 圆半径方向渐变


- (void)drawRadialGradient:(CGContextRef)context

path:(CGPathRef)path

startColor:(CGColorRef)startColor

endColor:(CGColorRef)endColor

{

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGFloat locations[] = { 0.0, 1.0 };

    

    NSArray *colors = @[(__bridgeid) startColor, (__bridgeid) endColor];

    

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);

    

    

    CGRect pathRect = CGPathGetBoundingBox(path);

    CGPoint center = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));

    CGFloat radius = MAX(pathRect.size.width / 2.0, pathRect.size.height / 2.0) * sqrt(2);

    

    CGContextSaveGState(context);

    CGContextAddPath(context, path);

    CGContextEOClip(context);

    

    CGContextDrawRadialGradient(context, gradient, center, 0, center, radius, 0);

    

    CGContextRestoreGState(context);

    

    CGGradientRelease(gradient);

    CGColorSpaceRelease(colorSpace);

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    //创建CGContextRef

    UIGraphicsBeginImageContext(self.view.bounds.size);

    CGContextRef gc = UIGraphicsGetCurrentContext();

    

    //创建CGMutablePathRef

    CGMutablePathRef path = CGPathCreateMutable();

    

    //绘制Path

    CGRect rect = CGRectMake(0, 100, 300, 200);

    CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));

    CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));

    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMinY(rect));

    CGPathCloseSubpath(path);

    

    //绘制渐变

    [self drawRadialGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];

    

    //注意释放CGMutablePathRef

    CGPathRelease(path);

    

    //Context中获取图像,并显示在界面上

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];

    [self.view addSubview:imgView];

}


3. CAShapeLayer作为layermask属性


CALayermask属性可以作为遮罩让layer显示mask遮住(非透明)的部分;CAShapeLayerCALayer的子类,通过path属性可以生成不同的形状,将CAShapeLayer对象用作layermask属性的话,就可以生成不同形状的图层。故生成颜色渐变有以下几个步骤:


生成一个imageView(也可以为layer)image的属性为颜色渐变的图片

生成一个CAShapeLayer对象,根据path属性指定所需的形状

CAShapeLayer对象赋值给imageViewmask属性

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    [self.view addSubview:self.firstCircle];

    _firstCircle.frame = CGRectMake(0, 0, 200, 200);

    _firstCircle.center = CGPointMake(CGRectGetWidth(self.view.bounds) / 2.0, CGRectGetHeight(self.view.bounds) / 2.0);

    CGFloat firsCircleWidth = 5;

    self.firstCircleShapeLayer = [self generateShapeLayerWithLineWidth:firsCircleWidth];

    _firstCircleShapeLayer.path = [self generateBezierPathWithCenter:CGPointMake(100, 100) radius:100].CGPath;

    _firstCircle.layer.mask = _firstCircleShapeLayer;

}


- (CAShapeLayer *)generateShapeLayerWithLineWidth:(CGFloat)lineWidth

{

    CAShapeLayer *waveline = [CAShapeLayer layer];

    waveline.lineCap = kCALineCapButt;

    waveline.lineJoin = kCALineJoinRound;

    waveline.strokeColor = [UIColor redColor].CGColor;

    waveline.fillColor = [[UIColor clearColor] CGColor];

    waveline.lineWidth = lineWidth;

    waveline.backgroundColor = [UIColor clearColor].CGColor;

    

    return waveline;

}


- (UIBezierPath *)generateBezierPathWithCenter:(CGPoint)center radius:(CGFloat)radius

{

    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2*M_PI clockwise:NO];

    

    return circlePath;

}


- (UIImageView *)firstCircle

{

    if (!_firstCircle) {

        self.firstCircle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"circleBackground"]];

        _firstCircle.layer.masksToBounds = YES;

        _firstCircle.alpha = 1.0;

    }

    

    return _firstCircle;

}



=========CGPATH===

//创建CGContextRef
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef gc = UIGraphicsGetCurrentContext();
    
    //=== 绘画逻辑 ===
    //创建用于转移坐标的Transform,这样我们不用按照实际显示做坐标计算
    CGAffineTransform transform = CGAffineTransformMakeTranslation(50, 50);
    //创建CGMutablePathRef
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddArc(path, &transform, 50, 50, 50, 0, 1.5 * M_PI, NO);
    CGPathMoveToPoint(path, &transform, 50, 0);
    CGPathAddLineToPoint(path, &transform, 50, 50);
    CGPathAddLineToPoint(path, &transform, 100, 50);
    
    //CGMutablePathRef添加到当前Context
    CGContextAddPath(gc, path);
    [[UIColor grayColor] setFill];
    [[UIColor blueColor] setStroke];
    CGContextSetLineWidth(gc, 2);
    //执行绘画
    CGContextDrawPath(gc, kCGPathFillStroke);
    
    //Context中获取图像,并显示在界面上
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgView];

======文字渐变

方法一:设置一张带有渐变的图片,

  UIColor *color=[UIColorcolorWithPatternImage:[UIImageimageNamed:@"带渐变色的图片"]];

方法二:


你可能感兴趣的:(iOS/oc)