如何在imagePicker(swift3)中更改图像方向

时间:2017-04-24 23:15:50

标签: ios swift swift3 imageview orientation

使用图像选择器功能拍摄照片时如何更改图像方向。我不是要尝试旋转imageView。我只是希望使用图像方向将图像上下颠倒显示在imageView中。

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate   {
@IBOutlet var displayImage: UIImageView!


var currentImageView: UIImageView?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.currentImageView?.image = image
    self.dismiss(animated: true)



}


@IBAction func takePhoto(_ sender: Any) {


    self.currentImageView = self.displayImage

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self

    imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
    imagePicker.allowsEditing = false
    self.present(imagePicker, animated: true, completion: nil)

}}

errors from answer

1 个答案:

答案 0 :(得分:0)

要直接回答您的问题,您可以旋转UIImage本身或旋转imageView。在这里,我已经为您编写了一个函数,您可以在UIImage的扩展中实现,它将颠倒图像。使用起来非常简单,虽然没有更多的上下文我不知道它是否正是您正在寻找的。你也可能会失去一些品质。

public func flipped() -> UIImage {
    var transform: CGAffineTransform = CGAffineTransform.identity
    transform = transform.translatedBy(x: self.size.width, y: self.size.height)
    transform = transform.rotated(by: CGFloat(Double.pi))
    guard let cgImage = self.cgImage, let colorSpace = cgImage.colorSpace, let context: CGContext = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return self }
    context.concatenate(transform)
    context.draw(cgImage, in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
    guard let transformed = context.makeImage() else { return self }
    return UIImage(cgImage: transformed)
}

将其添加到UIImage的扩展名中,您只需将UIImagePicker委托方法分配更改为self.currentImageView?.image = image.flipped()即可。