UIGraphicsImageRenderer
是在iOS 10中新引入的。我想知道是否有可能用它来旋转UIImage
(任何自定义角度)。我知道有CGContextRotateCTM
的classic way。
发布于 2020-07-10 20:29:08
基于@reza23的答案。你不需要调用UIGraphicsGetCurrentContext,你可以使用渲染器的上下文。
extension UIImage
{
public func rotate(angle:CGFloat)->UIImage
{
let radians = CGFloat(angle * .pi) / 180.0 as CGFloat
var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: radians)).size
// Trim off the extremely small float value to prevent core graphics from rounding it up
newSize.width = floor(newSize.width)
newSize.height = floor(newSize.height)
let renderer = UIGraphicsImageRenderer(size:newSize)
let image = renderer.image
{ rendederContext in
let context = rendederContext.cgContext
//rotate from center
context.translateBy(x: newSize.width/2, y: newSize.height/2)
context.rotate(by: radians)
draw(in: CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: size))
}
return image
}
}
https://stackoverflow.com/questions/39089148
复制相似问题