Update:使用以下代码表示SWIFT UIColor扩展的Gist.
如果你有greyscale image分,想要white become the tinting color分,那么kCGBlendModeMultiply
分是合适的.使用此方法时,高光不能比染色 colored颜色 亮.
相反,如果你有non-greyscale image,OR,你有highlights 103 shadows应该保留,混合模式kCGBlendModeColor
是可行的.当图像的亮度保持不变时,白色将保持白色,黑色将保持黑色.此模式仅用于着色-与Photoshop的Color
图层混合模式相同(免责声明:结果可能略有不同).
请注意,着色Alpha像素在iOS和Photoshop中都不能正常工作-半透明的黑色像素不会保持黑色.我更新了下面的答案来解决这个问题,花了相当长的时间才找到答案.
也可以使用混合模式kCGBlendModeSourceIn/DestinationIn
(而不是CGContextClipToMask
)之一.
如果要创建UIImage
,以下每个代码部分都可以由以下代码包围:
UIGraphicsBeginImageContextWithOptions (myIconImage.size, NO, myIconImage.scale); // for correct resolution on retina, thanks @MobileVet
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, myIconImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGRect rect = CGRectMake(0, 0, myIconImage.size.width, myIconImage.size.height);
// image drawing code here
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
下面是将透明图像着色为kCGBlendModeColor
的代码:
// draw black background to preserve color of transparent pixels
CGContextSetBlendMode(context, kCGBlendModeNormal);
[[UIColor blackColor] setFill];
CGContextFillRect(context, rect);
// draw original image
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, rect, myIconImage.CGImage);
// tint image (loosing alpha) - the luminosity of the original image is preserved
CGContextSetBlendMode(context, kCGBlendModeColor);
[tintColor setFill];
CGContextFillRect(context, rect);
// mask by alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawImage(context, rect, myIconImage.CGImage);
如果您的图像没有半透明像素,您也可以使用kCGBlendModeLuminosity
像素进行相反的操作:
// draw tint color
CGContextSetBlendMode(context, kCGBlendModeNormal);
[tintColor setFill];
CGContextFillRect(context, rect);
// replace luminosity of background (ignoring alpha)
CGContextSetBlendMode(context, kCGBlendModeLuminosity);
CGContextDrawImage(context, rect, myIconImage.CGImage);
// mask by alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawImage(context, rect, myIconImage.CGImage);
如果你不关心亮度,因为你只是得到了一个alpha通道的图像,应该用 colored颜色 着色,你可以用一种更有效的方式来做:
// draw tint color
CGContextSetBlendMode(context, kCGBlendModeNormal);
[tintColor setFill];
CGContextFillRect(context, rect);
// mask by alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawImage(context, rect, myIconImage.CGImage);
或者反过来说:
// draw alpha-mask
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, rect, myIconImage.CGImage);
// draw tint color, preserving alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
[tintColor setFill];
CGContextFillRect(context, rect);
玩得开心!