UIView drawRect():填充除多边形以外的所有内容



我需要用"reversed polygon"填充drawRect()方法中的UIView-视图中的所有内容都用某种颜色填充,除了多边形本身。

我有这个代码来画一个简单的多边形:

CGContextBeginPath(context);
for(int i = 0; i < corners.count; ++i)  
{
    CGPoint cur = [self cornerAt:i], next = [self cornerAt:(i + 1) % corners.count];
    if(i == 0)
        CGContextMoveToPoint(context, cur.x, cur.y);
    CGContextAddLineToPoint(context, next.x, next.y);
}
CGContextClosePath(context);
CGContextFillPath(context);

我发现了一个类似的问题,但在C#中,不是Obj-C:C#填充所有内容,而是GraphicsPath

可能最快的方法是设置剪辑:

// create your path as posted
// but don't fill it (remove the last line)
CGContextAddRect(context, self.bounds);
CGContextEOClip(context);
CGContextSetRGBFillColor(context, 1, 1, 0, 1);
CGContextFillRect(context, self.bounds);

其他两个答案都建议先填充一个矩形,然后在上面画出清晰的颜色。两者都省略了必要的混合模式。这是一个工作版本:

CGContextSetRGBFillColor(context, 1, 1, 0, 1);
CGContextFillRect(context, self.bounds);
CGContextSetBlendMode(context, kCGBlendModeClear);
// create and fill your path as posted

编辑:两种方法都要求backgroundColorclearColoropaque设置为NO。

第二次编辑:最初的问题是关于核心图形的。当然,还有其他方法可以掩盖视图的一部分。最显著的是CALayermask性质。

可以将此属性设置为包含剪辑路径的CAPathLayer实例,以创建模具效果。

在drawRect中,您可以将视图的背景颜色设置为您想要的颜色

    self.backgroundColor = [UIcolor redColor]; //set ur color

然后用你的方法画一个多边形。

CGContextBeginPath(context);
for(int i = 0; i < corners.count; ++i)  
{
    CGPoint cur = [self cornerAt:i], next = [self cornerAt:(i + 1) % corners.count];
    if(i == 0)
        CGContextMoveToPoint(context, cur.x, cur.y);
    CGContextAddLineToPoint(context, next.x, next.y);
}
CGContextClosePath(context);
CGContextFillPath(context);

希望能有所帮助。。快乐编码:)

创建一个新的CGLayer,用外部颜色填充它,然后用清晰的颜色绘制多边形。

layer1 = CGLayerCreateWithContext(context, self.bounds.size, NULL);
context1 = CGLayerGetContext(layer1);
[... fill entire layer ...]
CGContextSetFillColorWithColor(self.context1, [[UIColor clearColor] CGColor]);
[... draw your polygon ...]
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawLayerAtPoint(context, CGPointZero, layer1);

最新更新