【发布时间】:2015-03-06 11:35:45
【问题描述】:
目标:通过将图像与颜色相乘来为图像着色。
假设:根据 Apple 的 documentation,混合模式 kCGBlendModeMultiply“将源图像样本与背景图像样本相乘”。我从中了解到的是:R = S * D 代表 R、G、B 和 A。因此,如果乘法中的 2 个像素之一的 RED 值为 0.0,则生成的像素的 RED 将为 0.0。
结果:当颜色具有 alpha 时,它不会这样做。如果我使用 alpha 为 0.5 的黑色颜色,我希望图像的 alpha 为 1.0 的所有像素的结果都是黑色,alpha 为 0.5。
注意:颜色 alpha 为 1.0 时似乎可以正常工作。如果我使用 alpha 为 1.0 的黑色,则生成的图像是纯黑色图像,但这不是我在这里要问的。
预期结果:
- 图像的 alpha 应该是 0.5,因为这是颜色的 alpha,但是您看不到任何红色背景色透过图像,除了角落,因为我使用图像作为剪贴蒙版。
- 图像应该是完全灰色的,因为颜色的 R、G 和 B 值为 0.0。当您乘以 0 时,结果应该是 0。
下面的代码是我在操场上所做的复制/过去,所附图像显示了原始图像,色调颜色、图像视图中的结果图像和红色背景的图像视图(检查透明度)按此顺序。
import UIKit
// Get the image, its size, blend mode and tint color
var image = UIImage(named: "outlook-checkmark");
var size = image!.size;
var blendMode = kCGBlendModeMultiply;
var tintColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5);
// Create the graphic context, a frame with the image size
// and get the CGImage.
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
var context : CGContextRef = UIGraphicsGetCurrentContext();
var aRect = CGRectMake(0, 0, size.width, size.height);
var cgImage = image!.CGImage;
// Converting a UIImage to a CGImage flips the image,
// so apply an upside-down translation
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, blendMode);
CGContextDrawImage(context, aRect, cgImage);
// Set the mask to only tint non-transparent pixels
CGContextClipToMask(context, aRect, cgImage);
CGContextSetFillColorWithColor(context, tintColor.CGColor);
CGContextFillRect(context, aRect);
var returnImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
var imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100));
imageView.image = returnImage;
imageView.backgroundColor = UIColor.redColor();
【问题讨论】:
标签: ios macos swift core-graphics swift-playground