Dav*_*ave 38 iphone quartz-graphics uiview ios
我目前有两个UIViews:一个是红色背景,另一个是蓝色.蓝色视图是红色视图的子视图.我想做的是能够"剪掉"蓝色视图上的矩形,以便可以看到红色视图.你是怎么做的?
Jac*_*ues 75
您必须覆盖顶视图的drawRect方法.因此,例如,您可以创建一个HoleyView派生自的类UIView(您可以通过向项目添加新文件,选择Objective-C子类,并将"Subclass of"设置为UIView)来实现.在HoleyView,drawRect看起来像这样:
- (void)drawRect:(CGRect)rect {
// Start by filling the area with the blue color
[[UIColor blueColor] setFill];
UIRectFill( rect );
// Assume that there's an ivar somewhere called holeRect of type CGRect
// We could just fill holeRect, but it's more efficient to only fill the
// area we're being asked to draw.
CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
[[UIColor clearColor] setFill];
UIRectFill( holeRectIntersection );
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用"界面"构建器,请确保将多孔视图的类更改为HoleyView.您可以通过在Interface Builder中选择视图并在检查器中选择"Identity"窗格(最右侧的"i"图标)来选择.
您还必须使用以下代码段将顶视图设置为非透明,或者通过取消Opaque选中Interface Builder中视图属性中的复选框(您将在视图属性的View部分中找到它)并且将其背景颜色的不透明度设置为0%(背景颜色在同一部分中设置).
topView.opaque = NO;
topView.backgroundColor = [UIColor clearColor];
Run Code Online (Sandbox Code Playgroud)
如果你想做圆圈,你必须使用Core Graphics(也就是Quartz 2D).您可能希望阅读编程指南,该指南可在此处获得.
要绘制椭圆而不是矩形,您drawRect将看起来像这样:
- (void)drawRect:(CGRect)rect {
// Get the current graphics context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor( context, [UIColor blueColor].CGColor );
CGContextFillRect( context, rect );
if( CGRectIntersectsRect( holeRect, rect ) )
{
CGContextSetFillColorWithColor( context, [UIColor clearColor].CGColor );
CGContextFillEllipseInRect( context, holeRect );
}
}
Run Code Online (Sandbox Code Playgroud)
rag*_*age 35
所有其他答案都有道理,但很有可能用清晰的颜色绘制,或者说是擦除任何路径中的现有颜色,即使使用 - [UIBezierPath fill]或类似的便利方法.您所要做的就是根据您尝试实现的效果将上下文混合模式设置为适当的值,如下所示:
CGContextSetBlendMode(context, kCGBlendModeClear);
[[UIColor clearColor] set];
[myArbitraryPolygonPath fill];
Run Code Online (Sandbox Code Playgroud)
您可以选择大约24种不同的选项,查看CGContext参考.
val*_*ine 17
要绘制椭圆而不是矩形,只需将blendMode设置为清除:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor( context, [UIColor blackColor].CGColor );
CGContextFillRect( context, rect );
CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
CGContextSetFillColorWithColor( context, [UIColor clearColor].CGColor );
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextFillEllipseInRect( context, holeRect );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39844 次 |
| 最近记录: |