Why does a CAShapeLayer's stroke extend out of the frame?

后端 未结 2 737
灰色年华
灰色年华 2021-02-18 18:48

Here\'s sample code:

//Called by VC:

HICircleView *circleView = [[HICircleView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

// init of circle view

- (id)         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 19:03

    You'd rather choose your view's bounds property for calculation. Frame property won't work properly if it's origin is greater than (0,0). You can use CGRectInsets to adjust your circle's rectangle instead of performing transform calculations. This will automatically position the rectangle centered within the original rectangle.

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            CAShapeLayer *borderLayer = [CAShapeLayer layer];
            borderLayer.fillColor = [UIColor whiteColor].CGColor;
            CGFloat lineWidth = 5;
            CGRect rect = CGRectInset(self.bounds, lineWidth / 2, lineWidth / 2);
            borderLayer.path = [UIBezierPath bezierPathWithOvalInRect:rect].CGPath;
            borderLayer.strokeColor = [[UIColor redColor] CGColor];
            borderLayer.lineWidth = lineWidth;
            [self.layer addSublayer:borderLayer];
        }
        return self;
    }
    

提交回复
热议问题