gpt4 book ai didi

ios - 如何在 Swift 中旋转图像?

转载 作者:IT王子 更新时间:2023-10-29 05:01:05 24 4
gpt4 key购买 nike

我无法快速将图像旋转 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

}

下面是我不确定的代码

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))

最佳答案

设置ImageView图片

ImageView.transform = ImageView.transform.rotated(by: CGFloat(M_PI_2))

swift 5

ImageView.transform = ImageView.transform.rotated(by: .pi)        // 180˚

ImageView.transform = ImageView.transform.rotated(by: .pi / 2) // 90˚

ImageView.transform = ImageView.transform.rotated(by: .pi * 1.5) // 270˚

关于ios - 如何在 Swift 中旋转图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com