-1

我有一个UIView. 在这里面UIView,我有两个相交的子视图。我想在这两个子之间画一个共同的轮廓UIViews。我该怎么办?

说清楚:

[mainView addSubview:subView1];
[mainView addSubview:subView2];

我需要为这两个相交UIView的 s 画一个轮廓。

4

1 回答 1

0

您可以组合两个矩形的形状并从最终形状创建新的子图层。这一层将作为你的轮廓。

查看我的代码,它的完整注释:

//  Create shape of merged rectangles
UIBezierPath *outlinePath = [UIBezierPath bezierPathWithRect:subView1.frame];
[outlinePath appendPath:[UIBezierPath bezierPathWithRect:subView2.frame]];

//  Configure the outline
UIColor *outlineColor = [UIColor redColor];
CGFloat outlineWidth = 1.0f * [[UIScreen mainScreen] scale];

//  Create shape layer representing the outline shape
CAShapeLayer *outlineLayer = [CAShapeLayer layer];
outlineLayer.frame = mainView.bounds;
outlineLayer.fillColor = outlineColor.CGColor;
outlineLayer.strokeColor = outlineColor.CGColor;
outlineLayer.lineWidth = outlineWidth;

//  Set the path to the layer
outlineLayer.path = outlinePath.CGPath;

//  Add sublayer at index 0 - below everything already in the view
//  so it looks like the border
//  "outlineLayer" is in fact the shape of the combined rectangles
//  outset by layer border
//  Moving it at the bottom of layer hierarchy imitates the border
[mainView.layer insertSublayer:outlineLayer atIndex:0];

输出如下所示:

在此处输入图像描述

编辑:我起初误解了这个问题。以下是我的原始答案,其中概述了矩形交叉点。

您可以创建另一个表示交叉点的视图并将其添加到两个子视图上方。它的框架将是subView1subView2 frames 的交集。layer只需使用它的属性给它清晰的背景颜色和边框

您的代码可能如下所示:

//  Calculate intersection of 2 views
CGRect intersectionRect = CGRectIntersection(subView1.frame, subView2.frame);

//  Create intersection view
UIView *intersectionView = [[UIView alloc] initWithFrame:intersectionRect];
[mainView addSubview:intersectionView];

//  Configure intersection view (no background color, only border)
intersectionView.backgroundColor = [UIColor clearColor];
intersectionView.layer.borderColor = [UIColor redColor].CGColor;
intersectionView.layer.borderWidth = 1.0f;

在此处输入图像描述

于 2013-05-27T11:43:40.820 回答