CGContextClip()使用反向路径 [英] CGContextClip() using an inverted path

查看:838
本文介绍了CGContextClip()使用反向路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 CGContext 上剪切图形,但我需要它只是另一种方式,即我想添加几个矩形到我的剪切路径使用 CGContextAddRect(),并且剪辑应该以我添加到剪切路径的所有矩形不受任何绘制操作影响的方式完成。通常,它只是另一种方式,即绘图函数绘制到已添加到剪切路径的矩形,并留下未添加到剪切路径的区域不受影响。所以我想我需要的只是一个方法来逆转裁剪路径,然后调用 CGContextClip()。回到QuickDraw的日子,这可以通过使用区域,然后调用 XorRgn()为每个矩形轻松完成。但是用Quartz似乎更复杂。任何人都有一个简单的解决方案,以实现这一点,或者我需要我自己做所有这些路径逆转计算?

I want to have clipped drawing on my CGContext but I need it just the other way round, i.e. I want to add several rectangles to my clipping path using CGContextAddRect() and the clipping should be done in the way that all the rectangles that I have added to my clipping path stay unaffected by any drawing operations. Normally, it's just the other way round, i.e. drawing functions draw to the rectangles that have been added to the clipping path and leave the areas that haven't been added to the clipping path unaffected. So I guess what I need is just a way to reverse the clipping path before calling CGContextClip(). Back in the QuickDraw days, this could by easily done by using regions and then calling XorRgn() for every rectangle. But with Quartz it seems to be more complicated. Does anyone have an easy solution for achieving this or do I need to do all these path reversing calculations on my own?

推荐答案

您可以将整个边界添加为矩形,然后添加要从绘图中排除的矩形,并使用 CGContextEOClip

You could add your entire bounds as a rectangle, then add the rectangles you want to exclude from drawing and use CGContextEOClip.

示例:

- (void)drawRect:(NSRect)dirtyRect
    CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
    //Fill the background with gray:
    CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 1);
    CGContextFillRect(ctx, NSRectToCGRect(self.bounds));
    CGContextAddRect(ctx, NSRectToCGRect(self.bounds));
    //Add some rectangles:
    CGContextAddRect(ctx, CGRectMake(10, 10, 100, 100));
    CGContextAddRect(ctx, CGRectMake(120, 120, 50, 100));
    //Clip:
    CGContextEOClip(ctx);
    //Fill the entire bounds with red:
    CGContextSetRGBFillColor(ctx, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(ctx, NSRectToCGRect(self.bounds));
}

如果您在最后绘制图像而不是填充一个红色矩形。

The effect becomes more obvious if you draw an image at the end instead of filling a red rectangle.

这篇关于CGContextClip()使用反向路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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