1

我正在尝试创建一个循环进度指示器。不幸的是,仅从 setNeedsDisplay 第一次和最后一次调用 drawRect 例程,它不会创建我正在寻找的渐变填充模式。我创建了一个 UIView 子类,在其中填充背景,然后更新绘制进度,如下所示:

- (void)drawRect:(CGRect)rect
{
    // draw background
    CGFloat lineWidth = 5.f;
    UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath];
    processBackgroundPath.lineWidth = lineWidth;
    processBackgroundPath.lineCapStyle = kCGLineCapRound;
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.width / 2);
    CGFloat radius = (self.bounds.size.width - lineWidth) / 2;
    CGFloat startAngle = (2 * (float)M_PI / 2); // 90 degrees
    CGFloat endAngle = (2 * (float)M_PI) + startAngle;
    [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    [[UIColor grayColor] set];
    [processBackgroundPath stroke];

    // draw progress
    UIBezierPath *processPath = [UIBezierPath bezierPath];
    processPath.lineCapStyle = kCGLineCapRound;
    processPath.lineWidth = lineWidth;
    endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
    [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    [[UIColor blackColor] set];
    [processPath stroke];
}

我使用以下方法设置进度变量:

- (void)setProgress:(float)progress {
    _progress = progress;
    [self setNeedsDisplay];
}

然后,在将具有上述类的 UIView 分配给我的情节提要后,我只需在主视图控制器中调用附加的方法:

- (void)progressView:(CircularProgress *)activityView loopTime:(CGFloat)duration repeats:(BOOL)repeat {
    float portion = 0.0f;
    while (portion < 1.0f) {
        portion += 1/ (20.0 * duration);
        [activityView setProgress:portion];
        usleep(50000);
    }
}

同样, [self setNeedsDisplay] 仅在第一次和最后一次调用 drawRect 。在此先感谢您的帮助。

4

3 回答 3

5

usleep(50000)阻塞线程

改用NSTimer更新progressView。

[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES];
duration = 0;
...


- (void)updateProgressView {
    // Update the progress
  }
}
...
于 2013-05-23T14:42:02.590 回答
1

作为替代方案NSTimer,我还可以推荐使用CADisplayLink

CADisplayLink 对象是一个计时器对象,它允许您的应用程序将其绘图与显示器的刷新率同步。

您的应用程序创建一个新的显示链接,提供一个目标对象和一个选择器,以便在屏幕更新时调用。接下来,您的应用程序将显示链接添加到运行循环。

一旦显示链接与运行循环相关联,当屏幕内容需要更新时,就会调用目标上的选择器。

这将确保您的进度视图与设备帧速率大致同步重绘。

于 2013-05-23T14:49:49.047 回答
0
于 2013-05-23T14:47:14.593 回答