ios绘图系列(五)绘制渐变

iOS Core Graphics 的渐变可以分成径向渐变和辐射渐变.可以实现如下的图形:

可以在view 的 - (void)drawRect:(CGRect)rect实现
CGContextRef ctx = UIGraphicsGetCurrentContext();  
  
//创建一个RGB的颜色空间  
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,  
};  
  
//创建一个渐变的色值 1:颜色空间 2:渐变的色数组 3:位置数组,如果为NULL,则为平均渐变,否则颜色和位置一一对应 4:位置的个数  
CGGradientRef _gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));  
CGColorSpaceRelease(rgb);  
  
//获得一个CGRect  
CGRect clip = CGRectInset(CGContextGetClipBoundingBox(ctx), 20.0, 20.0);  
//剪切到合适的大小  
CGContextClipToRect(ctx, clip);  
//定义起始点和终止点  
CGPoint start = CGPointMake(20, 20);  
CGPoint end = CGPointMake(20, 100);  
//绘制渐变, 颜色的0对应start点,颜色的1对应end点,第四个参数是定义渐变是否超越起始点和终止点  
CGContextDrawLinearGradient(ctx, _gradient, start, end, kCGGradientDrawsBeforeStartLocation);  
  
//辐射渐变  
start = CGPointMake(100, 80);//起始点  
end = CGPointMake(100, 140); //终结点  
//辐射渐变 start:起始点 20:起始点的半径 end:终止点 40: 终止点的半径 这个辐射渐变  
CGContextDrawRadialGradient(ctx, _gradient, start, 20, end, 40, 0);  
UIKit提供一个CALayer的子类,专门绘制渐变,但是只支持线性渐变
CAGradientLayer *gradient = [CAGradientLayer layer];//创建渐变层  
gradient.frame = CGRectMake(20, 20, 100, 100);  
[self.view.layer addSublayer:gradient];  
//渐变层的颜色梯度数组  
gradient.colors = @[(__bridge id)[UIColor colorWithRed:204.0 / 255.0 green:224.0 / 255.0 blue:244.0 / 255.0 alpha:1].CGColor,  
                    (__bridge id)[UIColor colorWithRed:29.0 / 255.0 green:156.0 / 255.0 blue:215.0 / 255.0 alpha:1].CGColor,  
                    (__bridge id)[UIColor colorWithRed:0.0 / 255.0 green:50.0 / 255.0 blue:126.0 / 255.0 alpha:1].CGColor];  
//渐变层的相对位置,起始点为0,终止点为1,中间点为 (point-startpoint)/(endpoint-startpoint)  
gradient.locations = @[@0,@.5,@1];  
//渐变方向  
gradient.startPoint = CGPointMake(0, 0);  
gradient.endPoint = CGPointMake(0, 1);  

iOS绘图系列(一)概述

iOS绘图系列(二)画直线 CGContextMoveToPoint、CGContextAddLineToPoint、CGContextAddLines

iOS绘图系列(三)画弧线 CGContextAddArc、CGContextAddArcToPoint、CGContextAddCurveToPoint、UIBezierPath

iOS绘图系列(四)绘制文字和图像 CGContextDrawImage、drawInRect:、drawAtPoint:、UIGraphicsBeginImageContext

iOS绘图系列(五)绘制渐变 CGContextDrawLinearGradient、CGContextDrawRadialGradient、CAGradientLayer

iOS绘图系列(六)利用CAShapeLayer、UIBezierPath、CGPath绘制图像

转载于:https://my.oschina.net/gwlCode/blog/863107

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值