[英]Rotate image with UIGraphicsImageRenderer?
UIGraphicsImageRenderer
是在 iOS 10 中新引入的。我想知道是否有可能用它旋转UIImage
(任何自定义角度)。 我知道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
基于@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
}
}
仔细阅读文档,并且由于缺乏对这个问题的答复,我认为新的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
对应于在不改变其整体大小的情况下绘制旋转图像所需的矩形区域。 然后将图像旋转并在中心绘制。 有关更多信息,请参阅此帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.