Stroke masked CALayer in iOS

后端 未结 2 1683
抹茶落季
抹茶落季 2021-02-05 18:06

I\'m trying to create a label (or any other view for that matter) with one rounded corner and a stroke/border. I can achieve the former using the following code:



        
2条回答
  •  执笔经年
    2021-02-05 18:32

    You're on the right track with the shape layer. But you should have two different layers. First the mask layer as in your first example which masks your view (cuts off areas you don't want to be visible)

    Then you add the shape layer too, but not as mask layer. Also, make sure to not use borderWidth and borderColor, but stroke.

    //
    // Create your mask first
    //
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.label.bounds
                                          byRoundingCorners:UIRectCornerBottomRight
                                                cornerRadii:CGSizeMake(16.0f, 16.0f)];
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.label.bounds;
    maskLayer.path = maskPath.CGPath;
    self.label.layer.mask = maskLayer;    
    
    //
    // And then create the outline layer
    //
    CAShapeLayer *shape = [CAShapeLayer layer];
    shape.frame = self.label.bounds;
    shape.path = maskPath.CGPath;
    shape.lineWidth = 3.0f;
    shape.strokeColor = [UIColor whiteColor].CGColor;
    shape.fillColor = [UIColor clearColor].CGColor;
    [self.label.layer addSublayer:shape];
    

    Be aware that your stroke layer path should be inside (smaller than) the the path of the mask. Otherwise, the stroked path will be masked away by the mask layer. I've set the lineWith to 3 which makes it so you can see half of the width (1.5 px), and the other half will be outside the mask.

提交回复
热议问题