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

标签 ios cocoa-touch uiimage core-graphics cgcontext

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

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/

相关文章:

ios - 如何旋转图像但不切割边缘 IOS

swift - CIImage 转换为 UIImage

iphone - UINavigationItem -title 是否提供辅助功能?

ios - UIView 在 iOS7 中损坏但在 iOS8 中没有

objective-c - 动画消失后的 UIBarButtonItem

javascript - 如何为 iPhone 构建 React Native App?

ios - 为 UIImage 创建 alpha

objective-c - XCode 警告 - 尝试更改项目名称时复制 CMakeLists.txt

ios - 无论 UIViewContentMode 选择如何,部分屏幕视频预览都会失真

iphone - 使用委托(delegate)数组时出错