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:
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With