ios - 使用CoreGraphics在iOS中创建圆形渐变进度栏

标签 ios core-graphics uibezierpath

我想做这样的事情:

我试图用这样的核心Graphics来做到这一点:

    float radius = CGRectGetWidth(rect)/2.0f - self.circleBorderWidth/2.0f;
float angleOffset = 0;

UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
                                                     radius:radius
                                                 startAngle:-angleOffset
                                                   endAngle:(mCircleSegs + 1)/(float)kCircleSegs*M_PI*2 - angleOffset
                                                  clockwise:YES];

CGPathRef shape = CGPathCreateCopyByStrokingPath(aPath.CGPath, NULL, 3, kCGLineCapSquare, kCGLineJoinMiter, 1.0f);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddPath(ctx, shape);
CGContextClip(ctx);

AngleGradientLayer *angle = [[AngleGradientLayer alloc] init];
angle.colors = [NSArray arrayWithObjects:
                (id)[UIColor colorWithRed:0 green:0 blue:0 alpha:1].CGColor,
                (id)[UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor,
                nil];


CGContextClipToRect(ctx, self.bounds);
[angle drawInContext:ctx];

[angle release];

但是我认为我在这里走错了路。它看起来不像示例。 CoreGraphics能够绘制这样的图形吗?怎么样?

最佳答案

用作剪辑的贝塞尔曲线路径似乎只是一个圆圈的一小部分,而在您显示的图像中,该路径则更为复杂:一个圆圈的2个部分,由2条线链接,整个路径都有一个“环”形状。

这种方法应该可行,我将它用于具有相同外观的计时器。
尽管我没有直接使用AngleGradientLayer,但我修改了其- (CGImageRef)newImageGradientInRect:(CGRect)rect方法以返回UIImage。
但是我必须将此图像旋转+ PI / 2,因为巴甫洛夫(Pavlov)梯度角度梯度是水平开始的。

我使用UIImage,因为它是不会改变的背景,因此我在图层中保存了该UIImage的实例,并在每次更新剪切路径时绘制它

- (void)drawInContext:(CGContextRef)ctx
{

    UIBezierPath *currentPath = [self timerPath];
   // other drawing code for glow (shadow) and white stroke)
    CGContextAddPath(ctx, currentPath.CGPath);
    // clip !
    CGContextClip(ctx);
    CGContextDrawImage(ctx, self.bounds, _circularGradientImage.CGImage);

    //_circularGradientImage from modified newImageGradientInRect method.

}

这是我得到的:

关于ios - 使用CoreGraphics在iOS中创建圆形渐变进度栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924151/

相关文章:

ios - 如何绘制相对于 UIView 大小的点网格?

ios - 如何在 iOS 中获取表情符号路径

ios - 解析服务器云代码错误 141 无效函数

iphone - 如何从 unsigned char * 创建图像

ios - 按下 UITextField 的小十字按钮时的 Action

ios - drawRect 和 CGGraphicsContext 如何工作?

cocoa - 如何从 UIImage (Cocoa Touch) 或 CGImage (Core Graphics) 获取像素数据?

objective-c - 通过消除循环来简化曲线

ios - 如何获取 UIImage 中形状的 UIBezierPath 或以特定形状裁剪 UIImage

ios - 如何将 FMDB 导入 swift 框架