我正在使用 Swift 3,我正在 iPhone 7 上进行开发。
基于对如何旋转图像的大量搜索,我使用以下代码:
func sFunc_imageFixOrientation(img:UIImage) -> UIImage {
// No-op if the orientation is already correct
if (img.imageOrientation == UIImageOrientation.up) {
return img;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform:CGAffineTransform = CGAffineTransform.identity
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
}
if (img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: 0, y: img.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx:CGContext = CGContext(data: nil, width: Int(img.size.width), height: Int(img.size.height),
bitsPerComponent: img.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: img.cgImage!.colorSpace!,
bitmapInfo: img.cgImage!.bitmapInfo.rawValue)!
ctx.concatenate(transform)
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored
) {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.height,height:img.size.width))
} else {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.width,height:img.size.height))
}
// And now we just create a new UIImage from the drawing context
let cgimg:CGImage = ctx.makeImage()!
let imgEnd:UIImage = UIImage(cgImage: cgimg)
return imgEnd
}
在我的应用中,我使用人像模式为下面的一张纸拍照。
我希望图片横向显示在我的 UIImageView
中,所以我使用了上面的函数:
let rotatedImage = sFunc_imageFixOrientation(img : stillPicture.image!)
tempImageShow.contentMode = UIViewContentMode.scaleAspectFit
tempImageShow.image = rotatedImage
结果是:
如您所见,图像根本没有旋转。它在右侧填充了一个黑色矩形并被压扁以填充空间。如何让实际图像旋转,上面的代码有什么问题?
最佳答案
我真的不想涵盖所有情况,但只是为了您的图像,为了将其旋转成横向显示,以便文字正确向上,我编写了以下代码:
let im = UIImage(named:"picture")!
let r = UIGraphicsImageRenderer(size:
CGSize(width: im.size.height, height: im.size.width))
let outim = r.image { _ in
let con = UIGraphicsGetCurrentContext()!
con.translateBy(x: 0, y: im.size.width)
con.rotate(by: -.pi/2)
im.draw(at: .zero)
}
let iv = UIImageView(image:outim)
self.view.addSubview(iv)
结果:
这应该让您对程序有一个大概的了解。
关于ios - Swift 3 - 旋转后的图像无法在 ImageView 中正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729736/