我有UIView
。在这个UIView
里面,我有两个相交的子视图。我想在这两个子UIViews
之间绘制一个共同的轮廓。我怎么得到这个?
说清楚:
[mainView addSubview:subView1];
[mainView addSubview:subView2];
我需要为这些相交的UIView
s绘制轮廓。
答案 0 :(得分: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];
输出如下:
编辑:我一开始误解了这个问题。下面是我的原始答案,其中概述了交叉点。
您可以创建另一个将代表交叉点的视图,并将其添加到两个子视图上方。它的框架将是subView1
和subView2
frame
的交集。只需使用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;