UIGraphicsImageRenderer
是在iOS 10中新引入的。我想知道是否有可能用它旋转UIImage
(任何自定义角度)。我知道有classic way与CGContextRotateCTM
。
您可以设置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
通过文档,也由于缺乏对这个问题的回复,我认为新的UIGraphicsImageRenderer
是不可能的。以下是我在一天结束时解决的问题:
func changeImageRotation(forImage image:UIImage, rotation alpha:CGFloat) -> UIImage{
var newSize:CGSize{
let a = image.size.width
let b = image.size.height
let width = abs(cos(alpha)) * a + abs(sin(alpha)) * b
let height = abs(cos(alpha)) * b + abs(sin(alpha)) * a
return CGSize(width: width, height: height)
}
let size = newSize
let orgin = CGPoint(x: size.width/2, y: size.height/2)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: orgin.x, y: orgin.y)
context?.rotate(by: alpha)
context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage!
}
New Size
cor响应绘制旋转图像所需的矩形区域,而不改变其整体大小。然后旋转图像并在中心绘制。有关更多信息,请参阅此post。