Draw a common outline for the intersecting UIViews

2019-09-21 00:24发布

问题:

I have a UIView. Inside this UIView, I have two intersecting subviews. I want to draw a common outline between these two sub-UIViews. How do I get about this?

To make it clear:

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

I need to draw an outline for both these intersecting UIViews.

回答1:

You can combine shapes of both rectangles and create new sublayer from the final shape. This layer will act as your outline.

See my code, its fully commented:

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

Output looks like this:

Edit: I misunderstood the question at first. Below is my original answer which outlines rects intersection.

You can just create another view which will be representing the intersection and add it above the two subviews. It's frame would be intersection of the subView1 and subView2 frames. Just give it clear background color and border using its layer property

Your code could look like this:

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