更新:这是使用下面代码的 Swift UIColor 扩展的要点。
如果您有灰度图像并希望白色成为着色颜色,那么您kCGBlendModeMultiply
可以这样做。使用这种方法,您不能使高光比您的着色颜色更亮。
相反,如果您有一个非灰度图像,或者您有应该保留的高光和阴影,那么混合模式就是要走的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 通道的图像,你可以用一种更有效的方式来做到这一点:
// 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);
玩得开心!