我發現了幾種方法可以在Swift中逐級旋轉圖像,但沒有人能夠始終正常工作。我想將圖像左右旋轉90度。我認爲最好的一個是這樣的:Swift - 以度爲單位的圖像旋轉 - 變形結果
class func imageRotated(_ oldImage: UIImage, byDegrees 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.cgImage!, in: CGRect(x: -oldImage.size.width/2, y: -oldImage.size.height/2, width: oldImage.size.width, height: oldImage.size.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
它的工作原理,並做我想做的,但也有幾次,當它deformes結果,所以它不旋轉,只是圖像大小被改變,或者它是由180度和圖像尺寸旋轉被改變。
循環之前:
Afteer旋轉(菜單丟失,因爲它會自動隱藏):
有什麼奇怪的是,這發生在我參加的人像照片。當我在風景中拍攝照片時,旋轉效果很好(即使我嘗試多次旋轉,即使從風景轉換爲縱向,再次轉換爲風景,仍然可以正常工作)。
我看到了有關自動佈局約束問題進行一些討論,但我不知道這是否是我的問題,爲什麼它會爲某些情況下工作,對一些不會。我在收藏單元格中有照片,每個單元格都有第一個UIScrollView,而在UIScrollView中有UIImageView和照片。所有約束都設置爲界限。
如果它有幫助,我只想旋轉90或-90度。這可能會使方法更簡單,修復更容易。
感謝您的任何幫助。
嘗試使用 self.imageview。transform = CGAffineTransformMakeRotation(M_PI_2); – tejas
@tejas問題不在於旋轉'UIImageView',而是'UIImage'本身 – alexburtnik
@Libor請顯示您如何使用此方法並仔細檢查'imageView'的contentMode。它似乎是'ScaleToFill',它假設失真 – alexburtnik