ios - 在 Swift 中旋转 UIImage

标签 ios swift uiimage

我在 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/

相关文章:

xcode - IPA 中两次包含 Swift 库

ios - 尽管相机和节点共享原点,但 SceneKit 相机旋转错误

ios - 如何测试我的设备是 iphone 4 还是 iphone 5

ios - Realm 0.102.0 保存 RLMArray

ios - 在 iOS 中使用协议(protocol)传递多个值的正确方法

ios - 在图像上使用未解析的标识符

ios - UIImage RBG 值在保存到设备库时发生变化

ios - 左镜像照片的缩略图方向错误

ios - 使用 swift 为移动应用程序 IOS 上传的 Base 64 或图像文件

ios - 为什么从 FileManager 数据初始化的 UIImages 有错误的比例?