如何在iOS中使用弧形边缘绘制弧形?

在我的应用程序之一,我想绘制一个带圆angular的渐变弧。 像下面的图片

在这里输入图像说明

这是我迄今为止使用下面的代码所做的。

-(void)startArc { UIBezierPath *roundedArc = [self arcWithRoundedCornerAt:centerPoint startAngle:DEGREES_TO_RADIANS(-90) endAngle:DEGREES_TO_RADIANS(90) innerRadius:width-20 outerRadius:width cornerRadius:0]; CAShapeLayer *mask = [CAShapeLayer new]; [mask setPath:roundedArc.CGPath]; [mask setFrame:_outerView.bounds]; [mask setShouldRasterize:YES]; [mask setRasterizationScale:[UIScreen mainScreen].scale]; CAGradientLayer *gradient = [CAGradientLayer new]; [gradient setFrame:_outerView.bounds]; // [gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.86 green:0.91 blue:0.96 alpha:1.0f] CGColor],(id)[[UIColor colorWithRed:0.98 green:0.99 blue:0.99 alpha:1.0f] CGColor], nil]]; [gradient setColors:[NSArray arrayWithObjects:(id)[UIColor colorWithRed:0.19 green:0.64 blue:0.89 alpha:1.0].CGColor,(id)[UIColor colorWithRed:0.14 green:0.76 blue:0.56 alpha:1.0f].CGColor, nil]]; [gradient setMask:mask]; [_outerView.layer addSublayer:gradient]; } - (UIBezierPath *)arcWithRoundedCornerAt:(CGPoint)center startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle innerRadius:(CGFloat)innerRadius outerRadius:(CGFloat)outerRadius cornerRadius:(CGFloat)cornerRadius { CGFloat innerTheta = asin(cornerRadius / 2.0 / (innerRadius + cornerRadius)) * 2.0; CGFloat outerTheta = asin(cornerRadius / 2.0 / (outerRadius - cornerRadius)) * 2.0; UIBezierPath *path = [UIBezierPath bezierPath]; [path addArcWithCenter:center radius:innerRadius + cornerRadius startAngle:endAngle - innerTheta endAngle:startAngle + innerTheta clockwise:false]; [path addArcWithCenter:center radius:outerRadius - cornerRadius startAngle:startAngle + outerTheta endAngle:endAngle - outerTheta clockwise:true]; [path closePath]; return path; } 

用上面的代码,我已经实现了以下

在这里输入图像说明

有人可以让我知道如何实现圆润的边缘? 我已经实施了一个尖锐的边缘。

最简单的方法可能是:

  1. 创build一个弧形path(沿目标弧的中间)作为path
  2. 设置线宽(在你的情况下20)和线帽(圆帽)
  3. 将path转换为描边path(CGContextReplacePathWithStrokedPath)
  4. 继续使用现有的梯度代码

笔触会将无限窄的90度圆弧path转换成宽度为20像素且圆angular线结束的线条的轮廓线。

代码大概看起来像这样:

 - (UIBezierPath *)arcWithRoundedCornerAt:(CGPoint)center startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle innerRadius:(CGFloat)innerRadius outerRadius:(CGFloat)outerRadius cornerRadius:(CGFloat)cornerRadius context:(CGContext)context { CGFloat radius = (innerRadius + outerRadius) / 2.0; CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, true); CGContextSetLineCap(context, kCGLineCapRound); CGContextSetLineWidth(context, outerRadius - innerRadius); CGContextReplacePathWithStrokedPath(context) return [UIBezierPath bezierPathWithCGPath: CGContextCopyPath(context)]; }