How to improve drawing quality of CGLayer

785 views Asked by At

I use CoreGraphics for drawing circles in a custom SGCircleView. as I want the circles to be filled with a radial gradient when being touched, my appraoch is to draw one layer with the raw circle (SGCircleLayer) and then add another layer with the gradient. the problem is that the circles somehow look "grained".

that's the code in SGCircleLayer:

- (void) drawLayer: (CALayer *) layer inContext: (CGContextRef) ctx {
    UIGraphicsPushContext(ctx);
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect: CGRectInset(layer.bounds, CLineWidth / 2, CLineWidth / 2)];
    self.path = circlePath.CGPath;
    [[UIColor whiteColor] setStroke];
    circlePath.lineWidth = CLineWidth;
    [circlePath stroke];
    UIGraphicsPopContext();
}

for testing purposes I added another circle with exactly the same radius and line width drawn in drawRect of a custom SGCircleTestView which looks really smoth drawn.

this is the code of my drawRect in SGCircleTestView (smooth circle):

- (void) drawRect: (CGRect) rect {
    CGRect bounds = CGRectInset(rect, CLineWidth * 0.5, CLineWidth * 0.5);
    UIBezierPath* circlePath = [UIBezierPath bezierPathWithOvalInRect: bounds];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, CLineWidth2);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    [circlePath stroke];
}

what am I doing wrong in drawing code of my SGCircleLayer?

Preview

2

There are 2 answers

0
voidref On

It's likely you need to set the layer's contentsScale to the same as the screen.

layer.contentsScale = [UIScreen mainScreen].scale;
0
hfossli On