UIGraphicsImageRenderer
是在iOS 10中新引入的。我想知道是否有可能用它来旋转UIImage
(任何自定义角度)。我知道有CGContextRotateCTM
的classic way。
发布于 2016-11-26 02:04:26
您可以设置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
发布于 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
}
}
发布于 2016-08-24 05:54:46
浏览文档,也由于缺乏对这个问题的回复,我假设新的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
对应于绘制旋转图像而不更改其整体大小所需的矩形区域。然后旋转图像并将其绘制在中心。有关这方面的详细信息,请参阅此post。
https://stackoverflow.com/questions/39089148
复制相似问题