您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

自繪帶動畫的環形進度條,並讓數字與動畫同步

編輯:iOS 開發綜合

系統沒有現成的環形進度條,所以只能自己畫。本文示範用 CAShapeLayer 畫弧、用 CABasicAnimation 驅動 strokeEnd,再用一個子執行緒的計時器讓百分比數字跟著動。

為了方便重複使用,做成繼承 UIView 的自訂元件。

.h 檔

#import <UIKit/UIKit.h>

@interface LoopProgressView : UIView
@property (nonatomic, assign) CGFloat progress; // 傳入範圍 0 ~ 1
@end

.m 檔

幾個設計上的說明:

NSTimer 的觸發並不精準,這是系統的已知限制。

這裡每 0.01 秒觸發一次計時器,而動畫的 duration 直接設為 self.progress,兩者時間軸一致,數字與弧線就能同步走。

另外,實測時若把這個元件放進 UITableViewCell,原本跑在主 RunLoop 上的計時器會導致數字顯示延遲。解法是把計時器放到子執行緒;但子執行緒的 RunLoop 預設不帶 NSTimer,必須手動呼叫 [[NSRunLoop currentRunLoop] run] 把執行緒跑起來,計時器才會作動。

#import "LoopProgressView.h"
#import <QuartzCore/QuartzCore.h>

#define ViewWidth self.frame.size.width // 環形進度條的視圖寬度
#define ProgressWidth 2.5               // 圓環寬度
#define Radius ViewWidth / 2 - ProgressWidth // 圓環半徑

@interface LoopProgressView ()
{
    CAShapeLayer *arcLayer;
    UILabel *label;
    NSTimer *progressTimer;
}
@property (nonatomic, assign) CGFloat i;
@end

@implementation LoopProgressView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    _i = 0;

    CGContextRef progressContext = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(progressContext, ProgressWidth);
    CGContextSetRGBStrokeColor(progressContext, 209.0/255.0, 209.0/255.0, 209.0/255.0, 1);

    CGFloat xCenter = rect.size.width * 0.5;
    CGFloat yCenter = rect.size.height * 0.5;

    // 繪製環形進度條的底框
    CGContextAddArc(progressContext, xCenter, yCenter, Radius, 0, 2 * M_PI, 0);
    CGContextDrawPath(progressContext, kCGPathStroke);

    // 繪製進度環
    // 減去 M_PI * 0.5 可改變起始位置
    CGFloat to = self.progress * M_PI * 2;

    // 進度數字字級,可依視圖大小自行調整
    int fontNum = ViewWidth / 6;

    label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Radius + 10, ViewWidth / 6)];
    label.center = CGPointMake(xCenter, yCenter);
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont boldSystemFontOfSize:fontNum];
    label.text = @"0%";
    [self addSubview:label];

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path addArcWithCenter:CGPointMake(xCenter, yCenter)
                    radius:Radius
                startAngle:0
                  endAngle:to
                 clockwise:YES];

    arcLayer = [CAShapeLayer layer];
    arcLayer.path = path.CGPath;
    arcLayer.fillColor = [UIColor clearColor].CGColor;
    arcLayer.strokeColor = [UIColor colorWithRed:227.0/255.0 green:91.0/255.0 blue:90.0/255.0 alpha:0.7].CGColor;
    arcLayer.lineWidth = ProgressWidth;
    arcLayer.backgroundColor = [UIColor blueColor].CGColor;
    [self.layer addSublayer:arcLayer];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self drawLineAnimation:arcLayer];
    });

    if (self.progress > 1) {
        NSLog(@"傳入數值範圍為 0 - 1");
        self.progress = 1;
    } else if (self.progress < 0) {
        NSLog(@"傳入數值範圍為 0 - 1");
        self.progress = 0;
        return;
    }

    if (self.progress > 0) {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
        [thread start];
    }
}

- (void)newThread {
    @autoreleasepool {
        progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.01
                                                        target:self
                                                      selector:@selector(timeLabel)
                                                      userInfo:nil
                                                       repeats:YES];
        [[NSRunLoop currentRunLoop] run];
    }
}

// NSTimer 不會精準觸發
- (void)timeLabel {
    _i += 0.01;
    label.text = [NSString stringWithFormat:@"%.0f%%", _i * 100];
    if (_i >= self.progress) {
        [progressTimer invalidate];
        progressTimer = nil;
    }
}

// 定義動畫過程
- (void)drawLineAnimation:(CALayer *)layer {
    CABasicAnimation *bas = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    bas.duration = self.progress; // 動畫時間
    bas.delegate = self;
    bas.fromValue = [NSNumber numberWithInteger:0];
    bas.toValue = [NSNumber numberWithInteger:1];
    [layer addAnimation:bas forKey:@"key"];
}

@end

使用方式

只要幾行,傳入 0 到 1 之間的數值:

LoopProgressView *custom = [[LoopProgressView alloc] initWithFrame:CGRectMake(50, 100, 100, 100)];
custom.progress = 0.44;
[self.view addSubview:custom];

成果如下,進度條與數字同步推進:

若要在進度更新時動態改變數值(例如綁定下載進度),建議把 drawRect 的內容拆成「初始化一次」與「更新 progress」兩部分,避免每次重繪都重建計時器與動畫。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved