如何在Swift中旋转图像?

Tec*_*ain 45 animation uiview uiviewanimation ios swift

我无法将图像快速旋转90度.我写了下面的代码,但有一个错误,不编译

  func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> UIImage {

    //Calculate the size of the rotated view's containing box for our drawing space
    let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: oldImage.size.width, height: oldImage.size.height))
    let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat(M_PI / 180))
    rotatedViewBox.transform = t
    let rotatedSize: CGSize = rotatedViewBox.frame.size

    //Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize)
    let bitmap: CGContext = UIGraphicsGetCurrentContext()!

    //Move the origin to the middle of the image so we will rotate and scale around the center.
    bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)

    //Rotate the image context
    bitmap.rotate(by: (degrees * CGFloat(M_PI / 180)))

    //Now, draw the rotated/scaled image into the context
    bitmap.scaleBy(x: 1.0, y: -1.0)
    bitmap.draw(oldImage, in:  CGRect(origin: (x: -oldImage.size.width / 2,  y: -oldImage.size.height / 2, width:  oldImage.size.width, height: oldImage.size.height), size: oldImage.cgImage))

    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return newImage

  }
Run Code Online (Sandbox Code Playgroud)

下面是我不确定的代码

bitmap.draw(oldImage, in:  CGRect(origin: (x: -oldImage.size.width / 2,  y: -oldImage.size.height / 2, width:  oldImage.size.width, height: oldImage.size.height), size: oldImage.cgImage))
Run Code Online (Sandbox Code Playgroud)

Jay*_*iya 59

设置ImageView图像

ImageView.transform = ImageView.transform.rotated(by: CGFloat(M_PI_2))
Run Code Online (Sandbox Code Playgroud)

  • 对于**Swift 4**使用:`.pi/1`为180˚,`.pi/2`为90˚ (14认同)
  • 为什么选择M_PI_4?90度= M_PI_2 (5认同)
  • @JayeshMiruliya,同样在Swift 3中你可以使用`CGFloat.pi`常量(除以2 ofc) (3认同)
  • 对于动画-`UIView.animate(withDuration:3){self.needleImageView.transform = self.needleImageView.transform.rotated(by:CGFloat(Double.pi / 2))}`` (2认同)

小智 20

 let angle =  CGFloat(M_PI_2)
  let tr = CGAffineTransform.identity.rotated(by: angle)
  ImageView.transform = tr
Run Code Online (Sandbox Code Playgroud)

  • 我想旋转UIImage而不是imageview (8认同)

Cod*_*der 20

这是UIImage针对Swift 4.0的扩展,可以只旋转图像而无需使用UIImageView.成功测试了图像是否已旋转,而不仅仅是更改了exif数据.

import UIKit

extension UIImage {
    func rotate(radians: CGFloat) -> UIImage {
        let rotatedSize = CGRect(origin: .zero, size: size)
            .applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
            .integral.size
        UIGraphicsBeginImageContext(rotatedSize)
        if let context = UIGraphicsGetCurrentContext() {
            let origin = CGPoint(x: rotatedSize.width / 2.0,
                                 y: rotatedSize.height / 2.0)
            context.translateBy(x: origin.x, y: origin.y)
            context.rotate(by: radians)
            draw(in: CGRect(x: -origin.y, y: -origin.x,
                            width: size.width, height: size.height))
            let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return rotatedImage ?? self
        }

        return self
    }
}
Run Code Online (Sandbox Code Playgroud)

要执行180度旋转,您可以这样调用它:

let rotatedImage = image.rotate(radians: .pi)
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因无法旋转,则会返回原始图像.

  • CodeBender:我用`let rotationImage = image.rotate(radians:.pi)`来称呼它。图像为1433×2099。然后,我发现了另一个可以完美工作的解决方案:/sf/answers/3318196801/ (2认同)

Aar*_*sen 19

在一行中:

rotatedViewBox.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
Run Code Online (Sandbox Code Playgroud)

  • 这应该是最好的解决方案 (3认同)

iOS*_*iOS 10

在Swift 4.2和Xcode 10.0中

dropDownImageView.transform = dropDownImageView.transform.rotated(by: CGFloat(Double.pi / 2))
Run Code Online (Sandbox Code Playgroud)

如果要添加动画...

UIView.animate(withDuration: 2.0, animations: {
   self.dropDownImageView.transform = self.dropDownImageView.transform.rotated(by: CGFloat(Double.pi / 2))
})
Run Code Online (Sandbox Code Playgroud)


Sar*_*ran 9

通过 UIGraphics Context 旋转图像是比较繁重的操作。您可能会遇到质量下降和内存下降的问题。

我建议您应该尝试旋转图层或查看本身。

extension UIView {


    func rotate(degrees: CGFloat) {

        let degreesToRadians: (CGFloat) -> CGFloat = { (degrees: CGFloat) in
            return degrees / 180.0 * CGFloat.pi
        }
        self.transform =  CGAffineTransform(rotationAngle: degreesToRadians(degrees))

        // If you like to use layer you can uncomment the following line 
        //layer.transform = CATransform3DMakeRotation(degreesToRadians(degrees), 0.0, 0.0, 1.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用

yourImageView.rotate(degrees: 40)
Run Code Online (Sandbox Code Playgroud)


Smi*_*ash 6

你可以使用下面的代码Swift 3:

extension UIImage {

func fixImageOrientation() -> UIImage? {
    var flip:Bool = false //used to see if the image is mirrored
    var isRotatedBy90:Bool = false // used to check whether aspect ratio is to be changed or not

    var transform = CGAffineTransform.identity

    //check current orientation of original image
    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.rotated(by: CGFloat(M_PI));

    case .left, .leftMirrored:
        transform = transform.rotated(by: CGFloat(M_PI_2));
        isRotatedBy90 = true
    case .right, .rightMirrored:
        transform = transform.rotated(by: CGFloat(-M_PI_2));
        isRotatedBy90 = true
    case .up, .upMirrored:
        break
    }

    switch self.imageOrientation {

    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0)
        flip = true

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: self.size.height, y: 0)
        flip = true
    default:
        break;
    }

    // calculate the size of the rotated view's containing box for our drawing space
    let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint(x:0, y:0), size: size))
    rotatedViewBox.transform = transform
    let rotatedSize = rotatedViewBox.frame.size

    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize)
    let bitmap = UIGraphicsGetCurrentContext()

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    bitmap!.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0);

    // Now, draw the rotated/scaled image into the context
    var yFlip: CGFloat

    if(flip){
        yFlip = CGFloat(-1.0)
    } else {
        yFlip = CGFloat(1.0)
    }

    bitmap!.scaleBy(x: yFlip, y: -1.0)

    //check if we have to fix the aspect ratio
    if isRotatedBy90 {
        bitmap?.draw(self.cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.height,height: size.width))
    } else {
        bitmap?.draw(self.cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width,height: size.height))
    }

    let fixedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return fixedImage
}
Run Code Online (Sandbox Code Playgroud)