写在前面:
因项目需求,需要实现类似安卓角度渐变的效果,但iOS中CGGradientRef只支持线性渐变(CGContextDrawLinearGradient)和辐射渐变(CGContextDrawRadialGradient) 。
所以只得上网寻求解决方案,有大神推荐使用线性渐变和贝塞尔曲线,对于只略知贝塞尔曲线使用的我一时抓不到头绪。因此想到使用一张角度渐变的图片进行切割,进而实现想要的效果,以下是具体实现。
首先准备一张角度渐变的图片

经过对图片进行切割得到以下效果

实现思路:
通过CGContextAddArc 绘制一个圆弧,使用CGContextReplacePathWithStrokedPath进行反选路径后进行切割CGContextRef。最后绘制图片到CGContextRef上。
核心代码:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// 把当前上下文状态保存在栈中,防止以下操作影响圆形按钮的绘制
CGContextSaveGState(context);
CGContextSetLineWidth(context, self.lineWidth);
CGContextAddArc(context, center.x, center.y, radius, arcStartAngle, arcEndAngle, 1);
CGContextSetLineCap(context, kCGLineCapRound);
// 反选路径
CGContextReplacePathWithStrokedPath(context);
// 剪裁路径
CGContextClip(context);
// 绘制角度渐变
UIImage *gradientImg = [UIImage imageNamed:@"gradient"];
CGContextDrawImage(context, self.bounds, gradientImg.CGImage);
// 把保存在栈中的上下文状态取出来,恢复。上面那段代码设置的样式不会影响其他
CGContextRestoreGState(context);
补充内容--纯代码实现渐变滑动条
实现思路:
使用CGGradientRef(线性渐变or辐射渐变)绘制渐变色,然后对其进行切割,最终得到想要效果
显示效果:

代码:
// 创建RGB色彩空间,创建这个以后,context里面用的颜色都是用RGB表示
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
NSMutableArray *gradientObjColors = [NSMutableArray array];
[@[[UIColor redColor], [UIColor yellowColor]] enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UIColor class]]) {
[gradientObjColors addObject:(__bridge id)[obj CGColor]];
}
else if (CFGetTypeID((__bridge void *)obj) == CGColorGetTypeID()) {
[gradientObjColors addObject:obj];
}
else {
@throw [NSException exceptionWithName:@"CRGradientLabelError"
reason:@"Object in gradientColors array is not a UIColor or CGColorRef"
userInfo:NULL];
}
}];
CGGradientRef gradient =CGGradientCreateWithColors(NULL, (__bridge CFArrayRef)gradientObjColors, NULL);
// 释放色彩空间
CGColorSpaceRelease(baseSpace), baseSpace = NULL;
// 渐变色绘制方向
CGPoint startPoint = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMaxY(self.bounds));
CGPoint endPoint = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds));
// 用渐变色填充
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
// 释放渐变色
CGGradientRelease(gradient), gradient = NULL;
Demo地址:
https://github.com/chengqian0317/GradientSlider.git
最后说两句:
第一次写技术文章,如果有不正确的地方还望指正。谢谢!
网友评论