简体   繁体   English

将iOS Swift图像加载到UIImageView时旋转

[英]IOS Swift Image rotated when loaded into UIImageView

In my app, I have a button with which I open the Gallery as below: 在我的应用程序中,我有一个按钮可以用来打开图库,如下所示:

@IBAction func selectPhoto() {
    let photoPicker = UIImagePickerController()
    photoPicker.delegate = self
    photoPicker.sourceType = .PhotoLibrary
    self.presentViewController(photoPicker, animated: true, completion: nil)
}

I let the user select a photo and save it: 我让用户选择一张照片并保存:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage        
    let fileName:String = "logo.png"        
    let arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString        
    let pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)                UIImagePNGRepresentation(photoImageView.image!)!.writeToFile(pngFileName, atomically:true)        
    imageSave.setObject(fileName, forKey: "pngFileName")        
    self.dismissViewControllerAnimated(false, completion: nil)
}

Then from View controller, the pictures saved is shown everytime the user gets to the scene using below code. 然后从View控制器中,每次用户使用以下代码到达场景时,都会显示保存的图片。

 override func viewDidLoad() {
    super.viewDidLoad()

    if imageSave.stringForKey("pngFileName") != nil
    {
        let path = NSSearchPathForDirectoriesInDomains(
            .DocumentDirectory, .UserDomainMask, true)[0] as NSString
        let fileName = NSUserDefaults.standardUserDefaults()
            .stringForKey("pngFileName")
        let imagePath = path.stringByAppendingPathComponent(fileName!)
        let image = UIImage(contentsOfFile: imagePath )            
        photoImageView.image = image

    }

Problem : When the image loads back onto the UIImageView, the orientation of the picture is sometimes rotated right by 90 degrees, sometimes rotated left by 90 degrees or sometimes shown as it was saved. 问题:当图像重新加载到UIImageView上时,图片的方向有时会向右旋转90度,有时会向左旋转90度,有时会显示为保存状态。

Please let me know what I am doing wrong here. 请让我知道我在做什么错。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

I had the same problem, because of different rect sizes where the photo is shown. 我遇到了同样的问题,因为显示照片的矩形尺寸不同。 You could do a trick and save instead of the original image a copied version. 您可以采取一些技巧,并保存复制版本而不是原始图像。 This will discard the rotation problem, which is actually a fitting issue. 这将丢弃旋转问题,而这实际上是一个拟合问题。

let imageName = info[UIImagePickerControllerOriginalImage] as! UIImage
let thumb1 = UIImageJPEGRepresentation(imageName, 0.8)
btnImageView.image = UIImage(data: thumb1!)

This is just a quick and dirty answer, but worked for me. 这只是一个快速而肮脏的答案,但是对我有用。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM