我正在尝试将UIView的底部两个角弄圆,并使图层的边框也显示为圆角。我目前正在做:

UIRectCorners corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;
CGSize radii = CGSizeMake(kThisViewCornerRadius, kThisViewCornerRadius);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:myView.bounds
                                           byRoundingCorners:corners
                                                 cornerRadii:radii];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
[maskLayer setPath:path.CGPath];
myView.layer.mask = maskLayer;

这对于普通 View 来说效果很好。但是,myView的图层设置了borderColorborderWidth,并且从屏幕截图中可以看到,该图层的边框没有变圆:

我还尝试了对UIView进行子类化,并从[CAShapeLayer layer]返回+[Class layerClass],并将 View 的图层设置为形状图层,但是边框最终出现在 View 的 subview 下方。

是否可以将 View 的某些角弄成圆角,围绕该 View 的图层的边界并在该图层的边界下裁剪 subview ?

请注意,这不是关于如何拐弯一些拐角而不是其他拐角,而是如何使笔划正确地表现。

最佳答案

感谢David Rönnqvist的评论,我找到了一种新的思考方式。

我试图将拐角处的圆角和笔触全部放在一层上。取而代之的是,我将其分为两层:一层 mask View 的图层以圆角化,另一层遮盖 View 的笔触。

UIView *containerView = [[UIView alloc] initWithFrame:someFrame];

UIRectCorners corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;
CGSize radii = CGSizeMake(kThisViewCornerRadius, kThisViewCornerRadius);

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:myView.bounds
                                           byRoundingCorners:corners
                                                 cornerRadii:radii];

// Mask the container view’s layer to round the corners.
CAShapeLayer *cornerMaskLayer = [CAShapeLayer layer];
[cornerMaskLayer setPath:path.CGPath];
containerView.layer.mask = cornerMaskLayer;

// Make a transparent, stroked layer which will dispay the stroke.
CAShapeLayer *strokeLayer = [CAShapeLayer layer];
strokeLayer.path = path.CGPath;
strokeLayer.fillColor = [UIColor clearColor].CGColor;
strokeLayer.strokeColor = [UIColor redColor].CGColor;
strokeLayer.lineWidth = 2; // the stroke splits the width evenly inside and outside,
                           // but the outside part will be clipped by the containerView’s mask.

// Transparent view that will contain the stroke layer
UIView *strokeView = [[UIView alloc] initWithFrame:containerView.bounds];
strokeView.userInteractionEnabled = NO; // in case your container view contains controls
[strokeView.layer addSublayer:strokeLayer];

// configure and add any subviews to the container view

// stroke view goes in last, above all the subviews
[containerView addSubview:strokeView];

关于ios - 绕过UIView的一些角,也绕过 View 层的边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14866450/

10-12 12:50