iOS圆形进度条-带蒙版效果

效果图.png

自定义进度条
.h

#import <UIKit/UIKit.h>

@interface CircularProgressView : UIControl

@property (nonatomic) float progress;


@property (nonatomic, strong) UIColor *progressTintColor;

@property (nonatomic, strong) UILabel *centerLabel; /**< 记录进度的Label*/
@property (nonatomic, strong) UIColor *labelbackgroundColor; /**<Label的背景色 默认clearColor*/
@property (nonatomic, strong) UIColor *textColor; /**<Label的字体颜色 默认黑色*/
@property (nonatomic, strong) UIFont *textFont; /**<Label的字体大小 默认15*/

- (void)setProgress:(float)progress animated:(BOOL)animated;

@end

.m

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

#define DEGREES_TO_RADIANS(x) (x)/180.0*M_PI
#define RADIANS_TO_DEGREES(x) (x)/M_PI*180.0
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height

@interface CircularProgressViewBackGroundLayer : CALayer

@property (nonatomic, strong) UIColor *tintColor;

@end

@implementation CircularProgressViewBackGroundLayer

- (id)init
{
    self = [super init];

    if (self) {
        self.contentsScale = [UIScreen mainScreen].scale;
    }

    return self;
}
- (void)setTintColor:(UIColor *)tintColor
{
    _tintColor = tintColor;
  
    [self setNeedsDisplay];
}

- (void)drawInContext:(CGContextRef)ctx
{
    CGContextSetFillColorWithColor(ctx, self.tintColor.CGColor);
    CGContextSetStrokeColorWithColor(ctx, self.tintColor.CGColor);

    CGContextStrokeEllipseInRect(ctx, CGRectInset(self.bounds, 1, 1));

    CGContextFillRect(ctx, CGRectMake(CGRectGetMidX(self.bounds) - 4, CGRectGetMidY(self.bounds) - 4, 0, 0));

}

@end

@interface CircularProgressView ()

@property (nonatomic, strong) CircularProgressViewBackGroundLayer *backgroundLayer;
@property (nonatomic, strong) CAShapeLayer *shapeLayer;

@end
@implementation CircularProgressView
{
    UIColor *_progressTintColor;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        [self commonInit];
    }

    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];

    if (self) {
        [self commonInit];
    }

    return self;
}

- (void)commonInit{

    _progressTintColor = [UIColor blackColor];
    self.labelbackgroundColor = [UIColor clearColor];
    self.textColor = [UIColor blackColor];
    self.textFont = [UIFont systemFontOfSize:15];
    // Set up the background layer

    CircularProgressViewBackGroundLayer *backgroundLayer = [[CircularProgressViewBackGroundLayer alloc] init];
    backgroundLayer.frame = self.bounds;
    backgroundLayer.tintColor = self.progressTintColor;
    [self.layer addSublayer:backgroundLayer];
    self.backgroundLayer = backgroundLayer;

    // Set up the shape layer

    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    shapeLayer.frame = self.bounds;
    shapeLayer.fillColor = nil;
    shapeLayer.strokeColor = self.progressTintColor.CGColor;

    [self.layer addSublayer:shapeLayer];
    self.shapeLayer = shapeLayer;

    [self startIndeterminateAnimation];
}
- (void)layoutSubviews{
    [super layoutSubviews];
//    [super addSubview:self.centerLabel];
    self.centerLabel.backgroundColor = self.labelbackgroundColor;
    self.centerLabel.textColor = self.textColor;
    self.centerLabel.font = self.textFont;
    self.centerLabel.text = @"0%";
    [self addSubview:self.centerLabel];
}

- (UILabel *)centerLabel
{
    if(!_centerLabel)
    {
        _centerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/2)];
        _centerLabel.center = CGPointMake(WIDTH/2, HEIGHT/2);
        _centerLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _centerLabel;
}
#pragma mark - Accessors

- (void)setProgress:(float)progress animated:(BOOL)animated
{
    _progress = progress;

    if (progress > 0) {
        BOOL startingFromIndeterminateState = [self.shapeLayer animationForKey:@"indeterminateAnimation"] != nil;
    
        [self stopIndeterminateAnimation];
    
        self.shapeLayer.lineWidth = 3;
    
        self.shapeLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
                                                          radius:self.bounds.size.width/2 - 2
                                                      startAngle:3*M_PI_2
                                                        endAngle:3*M_PI_2 + 2*M_PI
                                                       clockwise:YES].CGPath;
    
        if (animated) {
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
            animation.fromValue = (startingFromIndeterminateState) ? @0 : nil;
            animation.toValue = [NSNumber numberWithFloat:progress];
            animation.duration = 1;
            self.shapeLayer.strokeEnd = progress;
        
            [self.shapeLayer addAnimation:animation forKey:@"animation"];
        } else {
            [CATransaction begin];
            [CATransaction setDisableActions:YES];
            self.shapeLayer.strokeEnd = progress;
            [CATransaction commit];
        }
    } else {
        // If progress is zero, then add the indeterminate animation
        [self.shapeLayer removeAnimationForKey:@"animation"];
    
        [self startIndeterminateAnimation];
    }
}
- (void)setProgress:(float)progress
{
    [self setProgress:progress animated:NO];
}

- (void)setProgressTintColor:(UIColor *)progressTintColor
{
    if ([self respondsToSelector:@selector(setTintColor:)]) {
        [self setValue:progressTintColor forKey:@"tintColor"];
    } else {
        _progressTintColor = progressTintColor;
        [self tintColorDidChange];
    }
}

- (UIColor *)progressTintColor
{
    if ([self respondsToSelector:@selector(tintColor)]) {
        return [self valueForKey:@"tintColor"];
    } else {
        return _progressTintColor;
    }
}

#pragma mark - UIControl overrides

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    // Ignore touches that occur before progress initiates

    if (self.progress > 0) {
        [super sendAction:action to:target forEvent:event];
    }
}

#pragma mark - Other methods

- (void)tintColorDidChange
{
    self.backgroundLayer.tintColor = self.progressTintColor;
    self.shapeLayer.strokeColor = self.progressTintColor.CGColor;
}

- (void)startIndeterminateAnimation
{
    [CATransaction begin];
    [CATransaction setDisableActions:YES];

    self.backgroundLayer.hidden = YES;

    self.shapeLayer.lineWidth = 1;
    self.shapeLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
                                                      radius:self.bounds.size.width/2 - 1
                                                  startAngle:DEGREES_TO_RADIANS(348)
                                                    endAngle:DEGREES_TO_RADIANS(12)
                                                   clockwise:NO].CGPath;
    self.shapeLayer.strokeEnd = 1;

    [CATransaction commit];

    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    rotationAnimation.toValue = [NSNumber numberWithFloat:2*M_PI];
    rotationAnimation.duration = 1.0;
    rotationAnimation.repeatCount = HUGE_VALF;

    [self.shapeLayer addAnimation:rotationAnimation forKey:@"indeterminateAnimation"];
}

- (void)stopIndeterminateAnimation
{
    [self.shapeLayer removeAnimationForKey:@"indeterminateAnimation"];

    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.backgroundLayer.hidden = NO;
    [CATransaction commit];
}
@end


#import "ViewController.h"
#import "CircularProgressView.h"

@interface ViewController ()
@property (nonatomic, strong) NSTimer *updateTimer;
@property (nonatomic, weak) CircularProgressView *progressView;
@property (nonatomic, strong) UIView *coverView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:0.8];

    UIButton *startBtn = [[UIButton alloc]init];
    startBtn.frame = CGRectMake(100, 300, 50, 50);
    startBtn.backgroundColor = [UIColor cyanColor];
    [startBtn setTitle:@"start" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(startClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
}

- (void)startClick{

    UIView *cover = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    cover.backgroundColor = [UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:0.3];
    CircularProgressView *progressView = [[CircularProgressView alloc]initWithFrame:CGRectMake(150, 100, 100, 100)];
    [cover addSubview:progressView];
    self.progressView = progressView;

    UIButton *stopBtn = [[UIButton alloc]init];
    stopBtn.frame = CGRectMake(180, 380, 50, 50);
    stopBtn.backgroundColor = [UIColor cyanColor];
    [stopBtn setTitle:@"取消" forState:UIControlStateNormal];
    [stopBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    [cover addSubview:stopBtn];
    [[UIApplication sharedApplication].keyWindow addSubview:cover];
    self.coverView = cover;
    [self performSelector:@selector(beginUpdatingProgressView) withObject:nil afterDelay:0];
}
- (void)beginUpdatingProgressView
{
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];
}
- (void)updateProgress:(NSTimer *)timer
{
    if (self.progressView.progress+0.01 >=1) {
        [timer invalidate];
        [self cancelClick];
    } else {
        [self.progressView setProgress:self.progressView.progress + 0.01  animated:YES];
        self.progressView.centerLabel.text = [NSString stringWithFormat:@"%.02f%%", self.progressView.progress*100];
    }
}
- (void)cancelClick{
    [self.updateTimer invalidate];
    [self.coverView removeFromSuperview];
    self.coverView = nil;
}

DEMO地址:https://github.com/WSGNSLog/WSGCircularProgressView

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容

  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,396评论 2 45
  • 注:解读只是个人暂时的浅见。 【解读】 1、这一章老子描述了宇宙的起源,“道”在天地之前就存在了。也是道产生天地和...
    吾宗老孙子阅读 197评论 1 0
  • 今天是二零一七年三月二十八日,很快就到二十九日了。 不知道别人的大学是怎样的,我完全是在紧张又无为中度过的...
    江永阅读 195评论 1 0
  • 发展心理学 这类书非常多,大多数看到的关于介绍孩子特征的书,都逃不过发展心理学的三个领域:身体发展,心理发展和语言...
    A索Emma阅读 902评论 0 2
  • 走在繁华的街头,五颜六色的街灯和行色匆匆的人群,愈发显得人们孤孤单单。 一阵一阵略带凉意的微风吹起了我的长裙,有几...
    轻绾阅读 668评论 1 13