我有以下代码。我想要创建一个蓝色圆圈:
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。不是圆圈,是什么原因?
最佳答案
较新的方法是使用 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
}
关于ios - 试图创建一个彩色圆圈 UIImage,但它总是以方形结束。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313468/