CAShapeLayer rounded corners distortion

460 views Asked by At

I'm currently dealing with an iOS app asset generation in code ( creating CAShapeLayer and rendering it as an UIImage ). I'm having a problem with rounded corners getting distorted when drawing a bezier path for my layer and was wondering if someone has had the same issue?

Screenshot to visualize the problem :

https://i.stack.imgur.com/I8Jre.png

( Generated UIImage is used as a backgroundImage for UIButton )

Code used to create a layer :

CAShapeLayer * layer = [CAShapeLayer new];
[layer setBackgroundColor:[UIColor clearColor].CGColor];
[layer setFrame:CGRectMake(.0, .0, size.width, size.height)];
[layer setFillColor:[UIColor colorForKey:@"colour_1"].CGColor];
[layer setStrokeColor:[UIColor colorForKey:@"colour_4"].CGColor];
[layer setLineWidth:2.0];
[layer setPath:[UIBezierPath bezierPathWithRoundedRect:layer.frame  byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10.0, 10.0)].CGPath];

Turn it into an UIImage :

UIImage * imageFromCALayer(CALayer * layer) {
    UIGraphicsBeginImageContextWithOptions([layer frame].size, NO, [UIScreen mainScreen].scale);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}
2

There are 2 answers

0
Lily Ballard On

Why are you taking a CAShapeLayer and rasterizing it to an image? Just draw the path directly! Not only is that the correct way to generate an image, but it will give you more control over the drawing process.

0
Nein Danke On

Since your CAShapeLayer and the image have the same dimensions and you apply an outline (which is half inside and half outside the shapes path) the resulting image is cropped. So all you need to do is to add the width of the outline to the width and height of your resulting image.