如何在尊重图像的alpha蒙版的同时在UIImage上绘制形状

wil*_*lc2 9 iphone quartz-graphics uiimageview uiimage

我需要一个可以根据标志用颜色或黑白绘制自己的UIImageView:

  BOOL isGrey;
Run Code Online (Sandbox Code Playgroud)

我试图通过在Quartz blendmode设置为Color的情况下在原始图像上绘制一个黑色矩形来实现.除非它不尊重图像的alpha蒙版,否则它可以正常工作.

见插图: 替代文字http://img214.imageshack.us/img214/1407/converttogreyscaleillo.png

搜索谷歌和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];
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有一些我忘记设置的石英绘图模式?我通过Quartz编程指南看了一下,但很难从重叠和超链接的主题中提取出你需要的一点信息.

显然,我正在寻找适用于具有任何蒙版形状的图像的通用解决方案,而不仅仅是所示的圆圈.

wil*_*lc2 10

要在尊重图像的alpha蒙版时绘制形状,只需在绘制之前添加一行:

 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];
    }
Run Code Online (Sandbox Code Playgroud)

}