试图创建一个彩色圆圈 UIImage,但它总是以方形结束。为什么?

Trying to create a colored circle UIImage, but it always ends up square. Why?

我有以下代码。我想要创建一个蓝色圆圈:

class func circleFromColor(_ color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
    let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    guard let context = UIGraphicsGetCurrentContext() else { return nil }

    context.setFillColor(color.cgColor)
    context.fill(rect)

    let radius: CGFloat = 8.0 * UIScreen.main.scale
    let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
    maskPath.addClip()

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

但是每次 returns 图像都是蓝色正方形。不是圆圈,是什么原因?

较新的方法是使用 UIGraphicsImageRenderer,它会自动为您提供正确的点比例。路径也可以自行填充,因此不需要剪贴蒙版:

func circleFromColor(_ color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
  UIGraphicsImageRenderer(size: size).image { context in
    color.setFill()
    UIBezierPath(ovalIn: .init(origin: .zero, size: size)).fill()
  }
}

以下是旧方法:

func circleFromColor(_ color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
    let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    guard let context = UIGraphicsGetCurrentContext() else { return nil }

    context.setFillColor(color.cgColor)

    let radius: CGFloat = 8.0 * UIScreen.main.scale
    let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
    maskPath.addClip()
    maskPath.fill()

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}