How to draw a smooth circle with CAShapeLayer and UIBezierPath?

前端 未结 5 1502
闹比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 07:53

    I know this is an older question, but for those who are trying to work in the drawRect method and still having trouble, one small tweak that helped me immensely was using the correct method to fetch the UIGraphicsContext. Using the default:

    let newSize = CGSize(width: 50, height: 50)
    UIGraphicsBeginImageContext(newSize)
    let context = UIGraphicsGetCurrentContext()
    

    would result in blurry circles no matter which suggestion I followed from the other answers. What finally did it for me was realizing that the default method for getting an ImageContext sets the scaling to non-retina. To get an ImageContext for a retina display you need to use this method:

    let newSize = CGSize(width: 50, height: 50)
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
    let context = UIGraphicsGetCurrentContext()
    

    from there using the normal drawing methods worked fine. Setting the last option to 0 will tell the system to use the scaling factor of the device’s main screen. The middle option false is used to tell the graphics context whether or not you'll be drawing an opaque image (true means the image will be opaque) or one that needs an alpha channel included for transparencies. Here are the appropriate Apple Docs for more context: https://developer.apple.com/reference/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc

提交回复
热议问题