Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIBezierPath bezierPathWithArcCenter not properly centered

I have a view in which I want to draw a circle with UIBezierPath bezierPathWithArcCenter. My view's initWithFrame is as follows:

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self == nil) {
        return nil;
    }

    self.circleLayer = [CAShapeLayer layer];
    self.circleLayer.fillColor = UIColor.clearColor.CGColor;
    self.circleLayer.strokeColor = UIColor.blackColor.CGColor;
    self.circleLayer.lineWidth = 4;
    self.circleLayer.bounds = self.bounds;


    self.startAngle = 0.0;
    self.endAngle = M_PI *  2;
    CGPoint center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
    CGFloat radius = self.frame.size.height * 0.45;
    self.circleLayer.path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:self.startAngle endAngle:self.endAngle clockwise:YES].CGPath;

    [self.layer addSublayer:self.circleLayer];

    self.backgroundColor = UIColor.greenColor;

    return self;
}

I expected that would produce a black circle centered in my view. However, the actual output looks like this:
Actual output

What am I doing wrong?

EDIT The weirdest part is that it's drawn correctly after a fresh install of the app - any consecutive launches result in it being drawn like in the image attached. Why?

like image 925
mag_zbc Avatar asked Sep 04 '17 08:09

mag_zbc


2 Answers

Do not use view's center!

In my case, using ,

let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY)

for center point solved my problem.

like image 50
Murat Yasar Avatar answered Nov 15 '22 05:11

Murat Yasar


The reason for this seems to be a bug in iOS. The CAShapeLayer has its bounds set properly

self.circleLayer.bounds = self.bounds;

Upon inspecting it, the origin and size of the layer is fine, but only after first launch of the app after installing. Any subsequent launch of the app will result in its size being (0, 0). Removing the app and installing it again will result in the circle being drawn properly once.

I fixed it by setting the layer's frame again further down the road.

like image 33
mag_zbc Avatar answered Nov 15 '22 04:11

mag_zbc