实战CAGradientLayer 做圆形进度条

来源:互联网 发布:js get set 编辑:程序博客网 时间:2024/05/21 09:50

CAGradientLayer 主要用于渐变颜色。这次用它做了一个demo。如下图


以下是代码

//////////////// .h

#import <UIKit/UIKit.h>

@interface CustomRoundPropgressView : UIView {

    

}

- (id)initWithFrame:(CGRect)frame BKColor:(UIColor*)bkColor CurColor:(UIColor *)curColor;

-(void)curProgressValue:(float)value;

- (void)curTitleText:(float)value;

@end


/////////////////.m

#import "CustomRoundPropgressView.h"


@interface CustomRoundPropgressView () {

}

@property (strong, nonatomic) UIImageView *bkImageView;

@property (strong, nonatomic) CAGradientLayer *progress;

@property (strong, nonatomic) UILabel *titleLabel;

@end



@implementation CustomRoundPropgressView



- (id)initWithFrame:(CGRect)frame BKColor:(UIColor*)bkColor CurColor:(UIColor *)curColor {

    

    self = [super initWithFrame:frame];

    if (self) {

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];

        imageView.layer.cornerRadius =  frame.size.width/2;

        [imageView setBackgroundColor:bkColor];

        imageView.layer.masksToBounds = YES;

        self.bkImageView = imageView;

        [self addSubview:imageView];

        

        

        CAGradientLayer *pro = [[CAGradientLayer alloc]init];

        pro.frame = CGRectMake(0,0, frame.size.width,frame.size.height);

        pro.startPoint = CGPointMake(0.0, 0);//左上角(00)坐标,右下角为(11)坐标

        pro.endPoint = CGPointMake(0.0, 1);

        pro.colors = @[(id)curColor.CGColor,(id)[UIColor clearColor].CGColor];

        self.progress = pro;

        [imageView.layer addSublayer:pro];

        

        float lableHeight = 30.0;

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.bounds.size.height - lableHeight) /2, self.bounds.size.width, lableHeight)];

        label.textColor = [UIColor whiteColor];

        label.font = [UIFont systemFontOfSize:14.0];

        label.textAlignment = NSTextAlignmentCenter;

        self.titleLabel = label;

        [imageView addSubview:label];

    }

    return self;

}

-(void)curProgressValue:(float)value

{

    self.progress.locations = [NSArray arrayWithObjects:@(value),@(value), nil];

}

- (void)curTitleText:(float)value {

    self.titleLabel.text = [NSString stringWithFormat:@"%.f%@",value*100,@"%"];

}

@end


///// 调用地方

CustomRoundPropgressView *view = [[CustomRoundPropgressView alloc] initWithFrame:CGRectMake(40, 60, 120, 120) BKColor:[UIColor blueColor] CurColor:[UIColor redColor]];

    [view setBackgroundColor:[UIColor blackColor]];

    [self.view addSubview:view];

    float progress = 0.6;

    [view curProgressValue:progress];

    [view curTitleText:progress];


以下是CAGradientLayer的介绍

CAGradientLayer简介 


0 0
原创粉丝点击