ios - 如何围绕圆形 UIView 制作弯曲的进度条?

标签 ios objective-c uiview progress-bar

我想制作一个这样的圆形进度条,以及如何为其调整大小和属性(形状、颜色、宽度等)制作动画。

我试图围绕一个圆形透明 View 制作它。

从哪里开始?

谁有示例代码?

enter image description here

最佳答案

学习是无可替代的,但是一点帮助也不会遗漏,所以这里有一些代码片段可以为您完成任务。

这个概念是使用一个 CAShapeLayer 和一个 UIBezierPath,而进度只是设置 UIBezierPath 的 strokeEnd 属性。您需要声明一个 CAShapeLayer 并设置其属性。我们将其称为我们的 progressLayer。 (我不会提供完整的代码,只是提供指导和示例供您放在一起。)

    // setup progress layer
    // N.B borderWidth is a float representing a value used as a margin. 
    // pathwidth is the width of the progress path
    // obviously progressBounds is a CGRect specifying the Layer's Bounds
    [self.progressLayer setFrame:progressBounds];
    UIBezierPath *progressPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) radius:(bounds.size.height - self.borderWidth - self.pathWidth   ) / 2 startAngle: (5* -M_PI / 12)  endAngle: (2.0 * M_PI - 7 * M_PI /12)   clockwise:YES];
     self.progressLayer.strokeColor = [UIColor whiteColor].CGColor;
     self.progressLayer.lineWidth = 6.0f ;
     self.progressLayer.path = progressPath.CGPath;
     self.progressLayer.anchorPoint = CGPointMake(0.5f, 0.5f);
     self.progressLayer.fillColor = [UIColor clearColor].CGColor;
     self.progressLayer.position = CGPointMake(self.layer.frame.size.width / 2 - self.borderWidth / 2, self.layer.frame.size.height / 2 - self.borderWidth/2);
    [self.progressLayer setStrokeEnd:0.0f];

您显然需要将 progressLayer 添加到您的 View 层次结构中

然后您将需要一个简单的动画来插入进度条;

    // updateInterval is a float specifying the duration of the animation.
    // progress is a float storing the, well, progress. 
    // newProgress is a float 

    [self.progressLayer setStrokeEnd:newProgress];
    CABasicAnimation *strokeEndAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    strokeEndAnimation.duration = updateInterval;
    [strokeEndAnimation setFillMode:kCAFillModeForwards];
    strokeEndAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    strokeEndAnimation.removedOnCompletion = NO;
    strokeEndAnimation.fromValue = [NSNumber numberWithFloat:self.progress];
    strokeEndAnimation.toValue = [NSNumber numberWithFloat:newProgress];
    self.progress = newProgress;
    [self.progressLayer addAnimation:strokeEndAnimation forKey:@"progressStatus"];

在上图中,未进行的路径只不过是 progressLayer 后面的第二个完全描边层

哦,还有最后一点,您会发现圆是顺时针方向进行的。如果您花时间了解这里发生的事情,您将了解如何逆时针设置进度。

祝你好运......

关于ios - 如何围绕圆形 UIView 制作弯曲的进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849732/

相关文章:

objective-c - performSelectorOnMainThread : and dispatch_async() on main queue? 有什么区别

iphone - 检测 iPhone 日历约会冲突的 SQL 语句

ios - 如何在 Swift 中显示动态高度的 3*3 CollectionView 单元格

objective-c - 为 10.5+ 编写时我应该使用 Objective-C 垃圾收集吗?

ios - 无法设置 self.navigationItem.backBarButtonItem

ios - 如何以编程方式关闭 UISearchBar?

objective-c - 从 NSString 到 NSDate 的转换再返回

ios - 更新 View iOS

ios - 使用双击切换全屏操作

ios - iPad 横向 View 帧大小