项目需求
根据服务器端返回的参数,更改图片的颜色并保留透明度,点击查看Android下如何操作。
更改颜色
UIImage* originalImage = [UIImage imageNamed:@"btn_right_arrow_circled"];
UIImage* newImage = [Utils changeColor:[Utils colorOfHexString:color] ofImage:originalImage];
相关函数
+ (UIImage*)changeColor:(UIColor*)color ofImage:(UIImage*)image {
UIGraphicsBeginImageContext (image.size);
CGRect rect = CGRectMake (0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext (rect.size);
CGContextRef context = UIGraphicsGetCurrentContext ();
CGContextSaveGState (context);
[color setFill];
CGContextFillRect (context, rect);
//一定要将BlendMode设置为kCGBlendModeDestinationIn
CGContextSetBlendMode (context, kCGBlendModeDestinationIn);
[image drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext ();
UIGraphicsEndImageContext ();
return newImage;
}