我目前正在使用遮罩为现有图像着色。例如,我有一个带有黑色边框和圆形蒙版的白色图像(就像前两个图像一样)。然后,我可以创建第三种颜色(即绿色)的图像,该颜色在原始图像的中心具有绿色(因为那里存在遮罩)。
我正在使用的代码是这样(建议):
-(UIImage *)paintWithMask:(UIImage *)mask color:(UIColor *)color andSize:(CGSize)size{
UIImage *image = self;
UIImage *rotatedMask = [self rotateImage:mask]; //For some reason this is needed.
UIGraphicsBeginImageContextWithOptions(size, NO, image.scale);
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
[image drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextClipToMask(context, rect, [rotatedMask CGImage]);
CGContextFillRect(context, rect);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
}
我现在需要做的是仅使用蒙版(显然没有黑色边框)绘制绿色圆圈,如下所示:
有任何想法吗?非常感谢!!
最佳答案
没有CoreGraphics,有一种更简便的方法。只需执行以下操作:
-(UIImageView *)imageViewWithMask:(UIImage *)mask color:(UIColor *)color andSize:(CGSize)size{
UIImage *tempImage = mask;
tempImage = [tempImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIGraphicsBeginImageContextWithOptions(size, NO,0);
[tempImage drawInRect: CGRectMake(0,0,size.width,size.height)];
tempImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *iv = [[UIImageView alloc] initWithImage: tempImage];
iv.tintColor = color;
return iv;
}
关于ios - iOS使用 mask 和UIColor创建UIImage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24419749/