使用 UIGraphicsImageRenderer 旋转图像?

Chr*_*oph 3 uikit image-rendering swift ios10

UIGraphicsImageRenderer是在 iOS 10 中新引入的。我想知道是否有可能旋转UIImage它(任何自定义角度)。我知道还有就是经典的方式CGContextRotateCTM

rez*_*a23 5

您可以设置 UIGraphicsImageRenderer 来创建图像,然后调用 UIGraphicsGetCurrentContext() 并旋转上下文

let renderer = UIGraphicsImageRenderer(size:sizeOfImage)
let image = renderer.image(actions: { _ in
    let context = UIGraphicsGetCurrentContext()

    context?.translateBy(x: orgin.x, y: orgin.y)
    context?.rotate(by: angle)
    context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))
}
return image
Run Code Online (Sandbox Code Playgroud)

  • 我认为您应该使用渲染器的 context.cgContext 属性,而不是获取当前上下文,因为它是自动管理的。 (12认同)
  • 截至 2021 年 10 月 23 日,此代码不再有效。 (3认同)