我在 Swift 中使用 Xcode 6.0.1。我有一个 UIImage,我想使用旧图像作为源制作另一张图像,新图像以某种方式旋转...比如说垂直翻转。
这个问题已经有人回答了a few months ago .但是,即使情况相同,该解决方案对我也不起作用。
当我有
var image = UIImage(CGImage: otherImage.CGImage, scale: 1.0, orientation: .DownMirrored)
Xcode 提示“调用中有一个额外的参数‘scale’”。在查阅了 Apple 文档后,这没有任何意义,因为该版本的初始化程序确实采用了这三个参数。省略比例和方向参数确实可以解决问题,但会阻止我进行旋转。
我能找到的唯一其他引用是 this guy , 谁有同样的问题。
你怎么看?
我确实需要它在这个版本的 Xcode 上运行,所以如果有一种替代方法来执行旋转(我还没有找到)那将会很有用。
最佳答案
Swift 5 解决方案
我写了Pixel SDK它为这个问题提供了更强大的解决方案,否则这里是最简单的解决方案:
extension UIImage {
func rotate(radians: Float) -> UIImage? {
var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(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)
UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
let context = UIGraphicsGetCurrentContext()!
// Move origin to middle
context.translateBy(x: newSize.width/2, y: newSize.height/2)
// Rotate around middle
context.rotate(by: CGFloat(radians))
// Draw the image at its center
self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
要使用此解决方案,您可以执行以下操作
let image = UIImage(named: "image.png")!
let newImage = image.rotate(radians: .pi/2) // Rotate 90 degrees
关于ios - 在 Swift 中旋转 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27092354/