How to draw a smooth circle with CAShapeLayer and UIBezierPath?

前端 未结 5 1511
闹比i
闹比i 2020-12-07 07:14

I am attempting to draw a stroked circle by using a CAShapeLayer and setting a circular path on it. However, this method is consistently less accurate when rendered to the

5条回答
  •  无人及你
    2020-12-07 08:01

    Who knew there are so many ways to draw a circle?

    TL;DR: If you want to use CAShapeLayer and still get smooth circles, you'll need to use shouldRasterize and rasterizationScale carefully.

    Original

    enter image description here

    Here's your original CAShapeLayer and a diff from the drawRect version. I made a screenshot off my iPad Mini with Retina Display, then massaged it in Photoshop, and blew it up to 200%. As you can clearly see, the CAShapeLayer version has visible differences, especially on the left and right edges (darkest pixels in the diff).

    Rasterize at screen scale

    enter image description here

    Let's rasterize at screen scale, which should be 2.0 on retina devices. Add this code:

    layer.rasterizationScale = [UIScreen mainScreen].scale;
    layer.shouldRasterize = YES;
    

    Note that rasterizationScale defaults to 1.0 even on retina devices, which accounts for the fuzziness of default shouldRasterize.

    The circle is now a little smoother, but the bad bits (darkest pixels in the diff) have moved to the top and bottom edges. Not appreciably better than no rasterizing!

    Rasterize at 2x screen scale

    enter image description here

    layer.rasterizationScale = 2.0 * [UIScreen mainScreen].scale;
    layer.shouldRasterize = YES;
    

    This rasterizes the path at 2x screen scale, or up to 4.0 on retina devices.

    The circle is now visibly smoother, the diffs are much lighter and spread out evenly.

    I also ran this in Instruments: Core Animation and didn't see any major differences in the Core Animation Debug Options. However it may be slower since it's downscaling not just blitting an offscreen bitmap to the screen. You may also need to temporarily set shouldRasterize = NO while animating.

    What doesn't work

    • Set shouldRasterize = YES by itself. On retina devices, this looks fuzzy because rasterizationScale != screenScale.

    • Set contentScale = screenScale. Since CAShapeLayer doesn't draw into contents, whether or not it is rasterizing, this doesn't affect the rendition.

    Credit to Jay Hollywood of Humaan, a sharp graphic designer who first pointed it out to me.

提交回复
热议问题