IOS根据一组颜色达到进度条的颜色渐变效果

@interface UIImage (Gradient)  为UIImage添加方法

+ (UIImage*)gradientImageFromColors:(NSArray*)colors withSize:(CGSize)size;


#import "UIImage+Gradient.h"

@implementation UIImage (Gradient)

+ (UIImage*)gradientImageFromColors:(NSArray*)colors withSize:(CGSize)size {

if (size.width <= 0 || size.height <= 0) {

return nil;

}

NSMutableArray *ar = [NSMutableArray array];

for(UIColor *c in colors) {

[ar addObject:(id)c.CGColor];

}

UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);

CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);

CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);

CGPoint start = CGPointMake(0.0, 0.0);

CGPoint end = CGPointMake(size.width, 0.0);

CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

CGGradientRelease(gradient);

CGContextRestoreGState(context);

CGColorSpaceRelease(colorSpace);

UIGraphicsEndImageContext();

return image;

}

//根据传入的float值实时渐变

- (void)setCurrentProgress:(CGFloat)progress {

[currentProgressView mas_makeConstraints:^(MASConstraintMaker *make) {

make.removeExisting = YES;

make.left.equalTo(backgroundImageView.mas_left);

make.top.equalTo(backgroundImageView.mas_top);

make.height.equalTo(backgroundImageView.mas_height);

make.width.equalTo(backgroundImageView.mas_width).multipliedBy(progress);

}];

currentProgressView.image = [UIImage gradientImageFromColors:[NSArray arrayWithObjects:[UIColor colorWithRed:239.0f / 255.0f green:52.0f / 255.0f blue:40.0f / 255.0f alpha:1.0f], [UIColor colorWithRed:252.0f / 255.0f green:109.0f / 255.0f blue:100.0f / 255.0f alpha:1.0f], nil] withSize:CGSizeMake(size.width * progress, size.height)];

}

progressValueLabel.text = [NSString stringWithFormat:@"%.1f%%", progress * 100];

其中progress是传入的float值 动态获取

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • (一)Masonry介绍 Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布...
    木易林1阅读 2,385评论 0 3
  • Masonry是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了并具有高可读性...
    3dcc6cf93bb5阅读 1,826评论 0 1
  • iOS_autoLayout_Masonry 概述 Masonry是一个轻量级的布局框架与更好的包装AutoLay...
    指尖的跳动阅读 1,195评论 1 4
  • 有位法师去寺庙讲解佛经,待客僧捧上一杯茶招待法师。待客僧发现茶杯上有个小小的缺口,歉意地说道:"很抱歉,杯子有个缺...
    xcy无名阅读 475评论 0 0
  • 前言 昨天又收到一条来自阿里云安全方面的短信,说是服务器存在对外DDoS攻击,很明显又被人攻击了。还很有可能被拿到...
    尽情的嘲笑我吧阅读 166评论 0 3