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

问题描述 投票:0回答:1

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

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
}

但是,每次返回图像都是蓝色的SQUARE。不是一个圆圈,有什么用?

ios cocoa-touch uiimage core-graphics cgcontext
1个回答
1
投票

较新的方法是使用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
}
© www.soinside.com 2019 - 2024. All rights reserved.