7

鉴于:

  1. ctx一个带框架的 CGContextRef ( ){0,0,100,100}
  2. 和一个矩形 ( r),带框架{25,25,50,50}

将上下文剪辑到该矩形很容易:

CGContextClipToRect(ctx, r);

掩盖下面的红色区域(红色==面具)

在此处输入图像描述

但我想反转这个剪裁矩形以将其转换为剪裁蒙版。期望的结果是掩盖下面的红色部分(red == mask)

在此处输入图像描述

我想在运行时以编程方式执行此操作。

不想手动准备位图图像以与我的应用程序一起静态发布。

给定ctxand r,如何在运行时最容易/直接地做到这一点?

4

4 回答 4

18

Read about fill rules in the “Filling a Path” section of the Quartz 2D Programming Guide.

In your case, the easiest thing to do is use the even-odd fill rule. Create a path consisting of your small rectangle, and a much larger rectangle:

CGContextBeginPath(ctx);
CGContextAddRect(ctx, CGRectMake(25,25,50,50));
CGContextAddRect(ctx, CGRectInfinite);

Then, intersect this path into the clipping path using the even-odd fill rule:

CGContextEOClip(ctx);
于 2013-01-03T19:42:47.633 回答
3

CGContextClipToRects()您可以通过传递构成您想要的红框的矩形来剪辑上下文。

于 2013-01-03T19:32:44.657 回答
1

你能像往常一样做所有的绘画,然后做:

CGContextClearRect(ctx, r);

一切都完成后?

于 2013-01-03T19:29:37.090 回答
0

这是实现 rob 答案的有用扩展

extension UIBezierPath {
    func addClipInverse() {
        let paths = UIBezierPath()
        paths.append(self)
        paths.append(.init(rect: .infinite))
        paths.usesEvenOddFillRule = true
        paths.addClip()
    }
}
于 2021-04-12T03:11:19.580 回答