更新:以下のコードを使用したSwiftUIColor拡張機能の要点は次のとおりです。
グレースケール画像があり、白を着色色にしたい場合は、これが最適kCGBlendModeMultiply
な方法です。この方法では、ハイライトを色合いよりも明るくすることはできません。
逆に、グレースケール以外の画像がある場合、または保存する必要のあるハイライトとシャドウがある場合は、ブレンドモードkCGBlendModeColor
が最適です。画像の明るさが維持されるため、白は白のまま、黒は黒のままになります。このモードは、色付けのために作成されたものです。これは、Photoshopのレイヤーブレンドモードと同じColor
です(免責事項:結果がわずかに異なる場合があります)。
アルファピクセルの色付けは、iOSでもPhotoshopでも正しく機能しないことに注意してください。半透明の黒いピクセルは黒のままではありません。その問題を回避するために以下の回答を更新しました。見つけるのにかなり長い時間がかかりました。
kCGBlendModeSourceIn/DestinationIn
の代わりにブレンドモードの1つを使用することもできます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);
明るさを気にしない場合は、色で着色する必要があるアルファチャネルのある画像を取得しただけなので、より効率的な方法でそれを行うことができます。
// 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);
楽しむ!