【发布时间】:2017-02-23 10:41:39
【问题描述】:
我发现了几种在 Swift 中按度旋转图像的方法,但没有一种方法可以一直正常工作。我想将图像向左或向右旋转 90 度。我认为最好的是:
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
}
它可以工作并做我想做的事,但有几次它会变形结果,所以它没有旋转,只是改变了图像大小,或者旋转了 180 度并改变了图像大小。
旋转前:
旋转后(菜单因自动隐藏而丢失):
奇怪的是,当我拍摄肖像照片时会发生这种情况。当我在横向拍摄照片时,旋转效果很好(即使我尝试旋转几次,即使我从横向旋转到纵向,然后再旋转到横向,它仍然可以正常工作)。
我看到一些关于自动布局约束问题的讨论,但我不确定这是否是我的问题,以及为什么它在某些情况下有效而在某些情况下无效。我在集合单元格中有照片,每个单元格都有第一个 UIScrollView,而在 UIScrollView 中有带有照片的 UIImageView。所有约束都设置为边界。
如果有帮助,我只想旋转 90 或 -90 度。这可能会使方法更简单,更容易修复。
感谢您的帮助。
【问题讨论】:
-
尝试使用self.imageview.transform = CGAffineTransformMakeRotation(M_PI_2);
-
@tejas 问题不是关于旋转
UIImageView,而是UIImage本身 -
@Libor 请展示您如何使用此方法并仔细检查您的
imageView中的contentMode。好像是ScaleToFill,假设失真
标签: ios swift image rotation uigraphicscontext