效果:
代码:
-(UIImage *)createGradientRingImage:(CGFloat)radius width:(CGFloat)width gradient:(NSArray <UIColor *>*)gradient{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(2*radius, 2*radius),NO,[UIScreen mainScreen].scale); //开始画线
//生成圆环上部分
UIImage *upperImage = [self createGradientSemiCircleImageRadius:radius width:width gradient:gradient upper:YES];
//生成圆环下部分
UIImage *image = [self createGradientSemiCircleImageRadius:radius width:width gradient:gradient upper:NO];
//合并成一个圆环
[upperImage drawInRect:CGRectMake(0, 0, radius*2, radius)];
[image drawInRect:CGRectMake(0, radius, radius*2, radius)];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
-(UIImage *)createGradientSemiCircleImageRadius:(CGFloat)radius width:(CGFloat)width gradient:(NSArray <UIColor *>*)gradient upper:(BOOL)upper{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(2*radius, radius),NO,[UIScreen mainScreen].scale); //开始画线
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetLineWidth(context, width);
//绘制半圆环
if (upper) {
CGContextAddArc(context, radius, radius, radius-width*0.5, M_PI, 2*M_PI, 0);
}else{
CGContextAddArc(context, radius, 0, radius-width*0.5, 0, M_PI, 0);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSMutableArray *colorArray = [NSMutableArray array];
for (UIColor *color in gradient) {
[colorArray addObject:(id)color.CGColor];
}
//null标识渐变色均匀分布
CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colorArray, NULL);
// 释放色彩空间
CGColorSpaceRelease(colorSpace);
CGContextReplacePathWithStrokedPath(context);
CGContextClip(context);
// 4. 用渐变色填充
//圆环是逆时针分布,所以上半部分圆环渐变色从-2*radius到28radius
//下半部分圆环从2*radius到-2radius
if (upper) {
CGContextDrawLinearGradient(context, gradientRef, CGPointMake(-radius*2, radius), CGPointMake(radius*2, radius), 0);
}else{
CGContextDrawLinearGradient(context, gradientRef, CGPointMake(radius*2, radius), CGPointMake(-radius*2, radius), 0);
}
// 释放渐变色
CGGradientRelease(gradientRef);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
//拉伸当前图像
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
return theImage;
}