作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要一个可以根据标志以彩色或黑白方式绘制自身的 UIImageView:
BOOL isGrey;
我试图通过在原始图像顶部绘制一个黑色矩形并将 Quartz 混合模式设置为“颜色”来实现此目的。这是可行的,只是它不尊重图像的 alpha 蒙版。
参见插图: alt text http://img214.imageshack.us/img214/1407/converttogreyscaleillo.png
搜索 Google 和 SO,我找到并尝试了几种解决方案,但没有一个尊重掩码。
以下是生成上面“我得到的”图像的代码:
- (void)drawRect:(CGRect)rect {
if (isGrey) {
CGContextRef context = UIGraphicsGetCurrentContext();
// flip orientation
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw the image
CGContextDrawImage(context, self.bounds, self.image.CGImage);
// set the blend mode and draw rectangle on top of image
CGContextSetBlendMode(context, kCGBlendModeSaturation);
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextFillRect(context, rect);
} else {
[self.image drawInRect:rect];
}
}
是否有一些我忘记设置的 Quartz 绘图模式?我已经阅读了《Quartz 编程指南》,但是很难从重叠和超链接的主题中提取您需要的一点信息。
显然,我正在寻找一种通用解决方案,该解决方案适用于具有任何 mask 形状的图像,而不仅仅是显示的圆圈。
最佳答案
要在尊重图像的 Alpha mask 的同时绘制形状,只需在绘制之前添加一行:
CGContextClipToMask(context, self.bounds, image.CGImage);
// example usage
- (void)drawRect:(CGRect)rect {
if (isGrey) {
CGContextRef context = UIGraphicsGetCurrentContext();
// flip orientation
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw the image
CGContextDrawImage(context, self.bounds, self.image.CGImage);
// set the blend mode and draw rectangle on top of image
CGContextSetBlendMode(context, kCGBlendModeColor);
CGContextClipToMask(context, self.bounds, image.CGImage); // respect alpha mask
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextFillRect(context, rect);
} else {
[self.image drawInRect:rect];
}
}
关于iphone - 如何在 UIImage 顶部绘制形状,同时尊重图像的 alpha 蒙版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1344767/
我是一名优秀的程序员,十分优秀!