Search code examples
iosobjective-ccore-graphicscore-animationuibezierpath

Setting the lineWidth of a UIBezierPath not working


I'm trying to draw a circle but the circle border always the same thin no matter what value I set. It feel like the line with always the default thinnest width.

- (void)drawCircleAtPoint:(CGPoint)center radius: (CGFloat)radius{

    UIBezierPath *path = [UIBezierPath bezierPath];

    path.lineWidth = 4; // Here
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;

    CGFloat r = radius;


    [path addArcWithCenter:center radius:r startAngle:0.0 endAngle:M_PI*2 clockwise:true];

    [path stroke];

    CAShapeLayer* layer = [CAShapeLayer new];
    layer.path = path.CGPath;
    layer.strokeColor = UIColor.redColor.CGColor;
    layer.fillColor = UIColor.yellowColor.CGColor;

    [layer addAnimation:[self getAnimation] forKey:nil];
    [self.layer addSublayer:layer];

}


- (CABasicAnimation*)getAnimation {

    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.duration = 1.2;
    animation.fromValue = @0;
    animation.toValue = @1;
    return animation;

}

This really drove me crazy.


Solution

  • You need to change the width of CAShapeLayer and not UIBezierPath. Like this :

    - (void)drawCircleAtPoint:(CGPoint)center radius: (CGFloat)radius{
        CGFloat r = radius;
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path addArcWithCenter:center radius:r startAngle:0.0 endAngle:M_PI*2 clockwise:true];
        [path setLineWidth:4]; // No need
        [path setLineCapStyle:kCGLineCapRound];
        [path setLineJoinStyle:kCGLineJoinRound];
        [path stroke];
        
        CAShapeLayer *layer = [CAShapeLayer new];
        layer.lineWidth = 4; // Add it here 
        layer.path = path.CGPath;
        layer.strokeColor = UIColor.redColor.CGColor;
        layer.fillColor = UIColor.yellowColor.CGColor;
        
        [layer addAnimation:[self getAnimation] forKey:nil];
        [self.view.layer addSublayer:layer];
    }