【问题标题】:Don't display subviews outside of UIBezierPath不要在 UIBezierPath 之外显示子视图
【发布时间】:2014-06-23 01:30:44
【问题描述】:

我有一个 UIView 是用以下方式绘制的:

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

    [bezierPath fill];
}

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

编辑:

为清楚起见,我将另一种视图定义为:

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

我将其中的大量作为子视图添加到第一个视图中,但我希望它们不会显示在椭圆形贝塞尔路径之外。有没有办法 a) 只将它们添加到椭圆形贝塞尔路径中而不是整个框架中,或者 b) 有一种方法可以从视图中剪掉椭圆形之外的所有内容?

【问题讨论】:

  • Cocoa 与 UIView 和 UIBezierPath 有什么关系?
  • UIBezierPath 是由 CoreGraphics 和 Foundation 构建的,它们被认为是 Cocoa 框架的一部分?
  • @orange 我认为 El Tomato 指的是 Cocoa 在 OS X 上,而 Cocoa Touch 在 iOS 上。

标签: objective-c cocoa-touch uiview uibezierpath


【解决方案1】:

为了将所有子视图剪辑到特定的 UIBezierPath,您需要设置视图的图层属性的掩码属性。如果您将 layer.mask 设置为该路径的 CAShapeLayer,则所有子视图都将被裁剪到该路径。

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

    // 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];

【讨论】:

  • 真的救了我的命!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多