如何在尊重图像的alpha蒙版的同时在UIImage上绘制形状 [英] How to draw a shape on top of a UIImage while respecting the image's alpha mask

查看:148
本文介绍了如何在尊重图像的alpha蒙版的同时在UIImage上绘制形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need a UIImageView that can draw itself in color or b/w according to a flag:

  BOOL isGrey;

我试图通过Quartz在原始图像上绘制一个黑色矩形来实现blendmode设置为Color。除非它不尊重图像的alpha蒙版,否则这样做。

I'm trying to do it by drawing a black rectangle on top of the original image with the Quartz blendmode set to Color. This works except it doesn't respect the image's alpha mask.

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

搜索Google和所以,我发现并尝试了几种解决方案,但没有人尊重面具。

Searching Google and SO, I found and tried several solutions but none respect the mask either.

以下是生成上面我得到的图片的代码:

Here is the code that produces the 'What I get' image above:

 - (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编程指南看了一下,但很难从重叠和超链接的主题中提取出你需要的一点信息。

Is there some Quartz drawing mode that I'm forgetting to set? I've looked thru the Quartz Programming Guide but is so hard to extract the one bit of info you need from the overlapping and hyperlinked subjects.

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

推荐答案

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

To draw a shape while respecting an image's alpha mask, just add one line before you draw:

 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];
    }

}

这篇关于如何在尊重图像的alpha蒙版的同时在UIImage上绘制形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆