总结iOS实现渐变颜色的三种方法

2020-01-18 16:31:19刘景俊

ios,开发实现颜色渐变,ios渐变色代码实现,颜色渐变

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 = @[(__bridge id) startColor, (__bridge id) 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];
}

ios,开发实现颜色渐变,ios渐变色代码实现,颜色渐变

三、以CAShapeLayer作为layer的mask属性

CALayer的mask属性可以作为遮罩让layer显示mask遮住(非透明)的部分;CAShapeLayer为CALayer的子类,通过path属性可以生成不同的形状,将CAShapeLayer对象用作layer的mask属性的话,就可以生成不同形状的图层。

故生成颜色渐变有以下几个步骤:

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

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