iOS改变图片的颜色

参考链接:https://onevcat.com/2013/04/using-blending-in-ios/

需求:改变一张图片的颜色,让它根据所选的颜色显示不同颜色。

//  UIImage+Tint.h

#import@interface UIImage (Tint)

- (UIImage *) imageWithTintColor:(UIColor *)tintColor;

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor;

@end

//  UIImage+Tint.m

#import "UIImage+Tint.h"

@implementation UIImage (Tint)

- (UIImage *) imageWithTintColor:(UIColor *)tintColor

{

return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];

}

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor

{

return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];

}

- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode

{

//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.

UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

[tintColor setFill];

CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);

UIRectFill(bounds);

//Draw the tinted image in context

[self drawInRect:bounds blendMode:blendMode alpha:1.0f];

if (blendMode != kCGBlendModeDestinationIn) {

[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];

}

UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return tintedImage;

}

@end

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

推荐阅读更多精彩内容