Round some corners of UIView and round the view’s layer’s border too

前端 未结 3 1339
鱼传尺愫
鱼传尺愫 2020-12-25 15:09

I am trying to round the bottom two corners of a UIView, and have the layer’s border show up rounded as well. I am currently doing:

UIRectCorners corners = U         


        
3条回答
  •  长情又很酷
    2020-12-25 16:02

    I figured out a new way of thinking about it, thanks to David Rönnqvist’s comment.

    I was trying to do the corner rounding and the stroke all in one layer. Instead, I broke it up into two layers: one to mask the view’s layer to round the corners, and the other in a view to add the stroke.

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

提交回复
热议问题