2012-08-29 74 views
1

我需要用drawRect()方法填充UIView中的'还原多边形' - 视图中的所有内容都用除多边形之外的某种颜色填充。UIView drawRect():填充除多边形以外的所有东西

我有了这个代码,以绘制一个简单多边形:

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#中,没有对象 - C:c# fill everything but GraphicsPath

+0

您可以用填充颜色填充整个视图,也比使用清晰的彩色 – Sohaib

+0

尝试同样喜欢在C#代码绘制您的多边形过它:CGContextAddRect(背景下,self.bounds)CGContextClosePath – Felix

回答

3

可能是最快的方法是设置一个片段:

// 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的实例,该实例包含剪辑路径以创建模具效果。

+0

谢谢,它的工作原理!第一种解决方案比较好,因为它不会裁剪整个视图,并且有可能在裁剪多边形内部绘制其他东西。另外,它以某种方式将“不透明”设置为“YES”。 :) – dreamzor

+0

@dreamzor很高兴我能帮到你。尽管如此,我不会依赖这个事实,即它使用'opaque = YES'。 –

+0

已经有一段时间了,但现在我发现这种方式太慢了。可以通过其他方式完成,使用CALayer还是其他方法?它看起来不是一个非常艰苦的绘画工作... – dreamzor

0

中的drawRectü可以设置背景UR与色彩观的颜色ü要

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); 

希望它可以帮助...编码快乐:)

+0

之前,我要建议的同样的事情@Resh32也有类似的想法 – Kezzer

+0

你不应该在'drawRect'中设置backgroundColor。此外,您的方法不会呈现透明的形状。 –

0

创建一个新的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); 
+0

你需要什么CGLayer?似乎不必要的开销给我。 –

+0

另外,使用默认混合模式(porter-duff over)绘制清晰的颜色是没有任何操作的。 –

+0

如果主环境已经绘制了其他元素(我不知道应用程序的其余部分),则需要CGLayer。 – Resh32