【问题标题】:Create a Round Gradient Progress Bar in iOS with CoreGraphics使用 CoreGraphics 在 iOS 中创建圆形渐变进度条
【发布时间】:2013-02-17 17:54:39
【问题描述】:

我想做这样的事情:

我试图用这样的核心图形来制作它:

    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 能画出这样的东西吗?怎么样?

【问题讨论】:

    标签: ios core-graphics uibezierpath


    【解决方案1】:

    您用作剪辑的贝塞尔路径似乎只是圆的一小部分,而在您显示的图像中,路径更复杂:圆的 2 个部分,由 2 条线连接,整个路径具有'环形'形状。

    这种方法应该可行,我将它用于具有相同外观的计时器。 虽然我没有直接使用AngleGradientLayer,但是我修改了它的- (CGImageRef)newImageGradientInRect:(CGRect)rect方法,返回一个UIImage。 但是我不得不将这张图片旋转 + PI/2,因为巴甫洛夫渐变角度渐变是水平开始的。

    我使用 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.
    
    }
    

    这是我得到的:

    【讨论】:

    • 问题不在于圆的 2 个部分。问题是渐变的绘制。我真的不知道你怎么能用核心图形画出这样的东西。
    • 是的!但如上图所示,当进度条为 20%、60%、80%、...时,第一个分数的结尾总是最白的。所以背景层不是解决方案。事实上,我想我们需要一个能够适应进展本身的背景......
    • 渐变也需要透明。在您的解决方案中,我看到一个非常小的白色边框。我也有这样的白色边框。我不确定如何删除它。
    • 我的例子中的白色边框是故意的 :)
    • 您应该避免重新绘制可以通过单个转换完成的操作:在您的情况下,如果“全白”始终位于开头,请使用相同的渐变图像,应用旋转以便它符合当前的进度...
    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多