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值 动态获取

你可能感兴趣的:(IOS根据一组颜色达到进度条的颜色渐变效果)