objective-c - 不要在 UIBezierPath 之外显示 subview

标签 objective-c cocoa-touch uiview uibezierpath

我有一个 UIView,它是用以下内容绘制的:

- (void)drawRect:(CGRect)rect
{
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, self.widthOfLine, self.heightOfLine)];

    [bezierPath fill];
}

并且其框架位于 iOS 窗口的中心。我想在此 View 中随机放置一堆较小的(5px x 5px) View ,我使用 arc4random() 函数并绘制 View 做得很好。但是,我似乎无法弄清楚如何切断 bezierPathWithOvalInRect 之外的所有 View ,它只会在第一个 UIView 框架中的任何位置显示它们。有人知道该怎么做吗?

编辑:

为了清楚起见,我将另一个 View 定义为:

- (void)drawRect:(CGRect)rect
{
    UIBezierPath *drawPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(self.xPosition, self.yPosition, self.width, self.width)];
    [[UIColor whiteColor] setFill];
    [drawPath fill];
}

我将大量这些作为 subview 添加到第一个 View 中,但我希望它们不要显示在椭圆形贝塞尔路径之外。有没有办法a)仅将它们添加到椭圆形贝塞尔曲线路径内,而不是添加到整个框架内,或者b)从 View 中剪掉椭圆形外部的所有内容?

最佳答案

为了将所有 subview 剪切到特定的 UIBezierPath,您需要设置 View 的 Layer 属性的 mask 属性。如果将layer.mask设置为该路径的CAShapeLayer,则所有 subview 都将被裁剪到该路径。

我使用以下代码在我的应用程序中执行此操作:

    // create your view that'll hold all the subviews that
    // need to be clipped to the path
    CGRect anyRect = ...;
    UIView* clippedView = [[UIView alloc] initWithFrame:anyRect];
    clippedView.clipsToBounds = YES;
    // now create the shape layer that we'll use to clip
    CAShapeLayer* maskingLayer = [CAShapeLayer layer];
    [maskingLayer setPath:bezierPath.CGPath];
    maskingLayer.frame = backingImageHolder.bounds;
    // set the mask property of the layer, and this will
    // make sure that all subviews are only visible inside
    // this path
    clippedView.layer.mask = maskingLayer;

    // now any subviews you add won't show outside of that path
    UIView* anySubview = ...;
    [clippedView addSubview:anySubview];

关于objective-c - 不要在 UIBezierPath 之外显示 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24357364/

相关文章:

ios - 如何判断 ViewController View 是否可见

ios - 自定义 UIView 使用 init(coder) 初始化,如何使用 init(frame) 初始化它

objective-c - 出货后在CoreData应用中引入iCloud,如何迁移旧数据

iphone - 有没有办法用AVPlayer区分直播流和点播文件流?

objective-c - 使用选择器从 MonoTouch 调用 Obj-C

objective-c - 如何在 iphone 的一个字符串中添加串联多个 NSString

iphone - MP4 文件不能在 MPMoviePlayerController 中播放?

objective-c - iOS:如何将 UIViewAnimationCurve 转换为 UIViewAnimationOptions?

ios - 在表 IOS 中选择单元格

objective-c - clang不编译一个简单的c文件