UIView的圆顶角并添加边框

ani*_*dhc 16 core-graphics objective-c uiview ios

我在一个圆角的圆类中有以下代码.我还想画一个边框.但边角没有显示在角落的圆角部分.

在此输入图像描述

这是代码

- (void) roundTopCorners:(CGFloat) radius
{
    self.layer.masksToBounds = YES;

    CGRect bounds = self.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;
    maskLayer.strokeColor = [UIColor redColor].CGColor;

    self.layer.mask = maskLayer;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*rry 39

掩模图层不会被绘制,仅用于计算蒙版.尝试:

-(void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
    CGRect bounds = self.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                                   byRoundingCorners:corners
                                                         cornerRadii:CGSizeMake(radius, radius)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;

    self.layer.mask = maskLayer;

    CAShapeLayer*   frameLayer = [CAShapeLayer layer];
    frameLayer.frame = bounds;
    frameLayer.path = maskPath.CGPath;
    frameLayer.strokeColor = [UIColor redColor].CGColor;
    frameLayer.fillColor = nil;

    [self.layer addSublayer:frameLayer];
}

-(void)roundTopCornersRadius:(CGFloat)radius
{
    [self roundCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) radius:radius];
}

-(void)roundBottomCornersRadius:(CGFloat)radius
{
    [self roundCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) radius:radius];
}
Run Code Online (Sandbox Code Playgroud)

您当前看到的帧是UITextField的常规帧,因此将帧样式设置为none.你还必须调整插图以弥补框架样式设置为无的事实,通常没有插入.

  • 这是一个很好的方法.但是,边框的厚度不合适.这是因为边框的笔划是掩模的一半和一半.它很容易修复 - 只需添加以下内容:`frameLayer.lineWidth = borderWidth*2;`其中borderWidth是您想要的边框宽度. (3认同)

Voj*_*bka 13

Swift版David Berry的回答:

func roundCorners(corners:UIRectCorner, radius:CGFloat) {
    let bounds = self.bounds

    let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius))

    let maskLayer = CAShapeLayer()
    maskLayer.frame = bounds
    maskLayer.path = maskPath.CGPath

    self.layer.mask = maskLayer

    let frameLayer = CAShapeLayer()
    frameLayer.frame = bounds
    frameLayer.path = maskPath.CGPath
    frameLayer.strokeColor = UIColor.redColor().CGColor
    frameLayer.fillColor = nil

    self.layer.addSublayer(frameLayer)
}

func roundTopCornersRadius(radius:CGFloat) {
    self.roundCorners([UIRectCorner.TopLeft, UIRectCorner.TopRight], radius:radius)
}

func roundBottomCornersRadius(radius:CGFloat) {
    self.roundCorners([UIRectCorner.BottomLeft, UIRectCorner.BottomRight], radius:radius)
}
Run Code Online (Sandbox Code Playgroud)