UIGraphicsImageRenderer
是在 iOS 10 中新引入的。我想知道是否有可能UIImage
与它一起旋转(任何自定义角度)。我知道有经典的方式CGContextRotateCTM
。
问问题
3498 次
3 回答
4
您可以设置 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
于 2016-11-25T18:04:25.613 回答
1
建立在@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
}
}
于 2020-07-10T12:29:07.953 回答
0
浏览文档,也由于缺乏对这个问题的答复,我认为新的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
对应于绘制旋转图像而不改变其整体大小所需的矩形区域。然后在中心旋转和绘制图像。有关这方面的更多信息,请参阅这篇文章。
于 2016-08-23T21:54:46.220 回答