2010-12-03 44 views
1

我正在为3.2及更高版本创建一个iPad应用程序。我的应用程序有一个覆盖视图,它具有半透明度,使得它下面的一切都变得更暗。在该视图中的中间我在此半透明度斩波一个孔让通过没有受伤的背景过滤器的一部分,与此代码:如何从父视图中移除具有圆角的UIView?

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGRect intersection = CGRectIntersection(hole.frame, rect); 
    CGContextClearRect(context, intersection); 
} 

此外,“洞”视图具有圆角,通过施加:

self.layer.cornerRadius = 4.25; 

这个工程除了一个小问题大 - 这些圆角都没有考虑到,所以被砍伤出洞具有方角而不是圆角。我需要解决这个问题,但我不知道如何。任何想法,例子,想法?

回答

3

以下是我最终得到它的工作。这会产生一个与“孔”UIView相同的框架,从自己(UIView)中切出它。这让你可以毫无阻碍地看到'洞'背后的任何东西。

- (void)drawRect:(CGRect)rect { 
    CGFloat radius = self.hole.layer.cornerRadius; 
    CGRect c = self.hole.frame; 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

     // this simply draws a path the same shape as the 'hole' view 
    CGContextMoveToPoint(context, c.origin.x, c.origin.y + radius); 
    CGContextAddLineToPoint(context, c.origin.x, c.origin.y + c.size.height - radius); 
    CGContextAddArc(context, c.origin.x + radius, c.origin.y + c.size.height - radius, radius, M_PI_4, M_PI_2, 1); 
    CGContextAddLineToPoint(context, c.origin.x + c.size.width - radius, c.origin.y + c.size.height); 
    CGContextAddArc(context, c.origin.x + c.size.width - radius, c.origin.y + c.size.height - radius, radius, M_PI_2, 0.0f, 1); 
    CGContextAddLineToPoint(context, c.origin.x + c.size.width, c.origin.y + radius); 
    CGContextAddArc(context, c.origin.x + c.size.width - radius, c.origin.y + radius, radius, 0.0f, -M_PI_2, 1); 
    CGContextAddLineToPoint(context, c.origin.x + radius, c.origin.y); 
    CGContextAddArc(context, c.origin.x + radius, c.origin.y + radius, radius, -M_PI_2, M_PI, 1); 

     // finish 
    CGContextClosePath(context); 
    CGContextClip(context); // this is the secret sauce 
    CGContextClearRect(context, c); 
} 
0

如果更改图层的cornerRadius属性,则还必须在相关视图上将clipsToBounds设置为YES,以便将内容剪切为圆角。

+0

clipsToBounds是您是否可以在接收器视图的边界之外绘制对象。换句话说,你可以在父UIView的边界之外画一个UIView的子视图吗?不知道这将如何帮助.. – Allyn 2010-12-03 21:54:00

+0

`cornerRadius`被合并到剪切路径(以粗略的方式),所以你必须启用裁剪才能使其对内容生效。 – 2010-12-03 21:57:33