很长时间没有更新博客了,最近一直在做项目,遇到了改变UIImage颜色和大小的问题,记录下来以供参考
利用类目的方法向系统类中扩展新的方法,不给大家过多的解释了,直接上代码了。
.h文件 中
#import <UIKit/UIKit.h>
@interface UIImage (UIImage_ChangeColor)
- (UIImage *)changeImageColorWithColor:(UIColor *)color;
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize;
@end
.m文件中
#import "UIImage+UIImage_ChangeColor.h"
@implementation UIImage (UIImage_ChangeColor)
- (UIImage *)changeImageColorWithColor:(UIColor *)color
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextClipToMask(context, rect, self.CGImage);
[color setFill];
CGContextFillRect(context, rect);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize
{
UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
[image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return reSizeImage;
}