iOS PNG Image rotated 90 degrees

后端 未结 6 1730
猫巷女王i
猫巷女王i 2020-11-28 05:22

In my iOS application I\'m writing, I deal with PNGs because I deal with the alpha channel. For some reason, I can load a PNG into my imageView just fine, but

6条回答
  •  清酒与你
    2020-11-28 05:39

    Took a few days, but I finally figured it out thanks to the answer @Dondragmer posted. But I figured I'd post my full solution.

    So basically I had to write a method to intelligently auto-rotate my images. The downside is that I have to call this method everywhere throughout my code and it is kind of processor intensive, especially when working on mobile devices, but the plus side is that I can take images, copy images, paste images, and save images and they all rotate properly. Here's the code I ended up using (the method isn't 100% complete yet, still need to edit memory leaks and what not).

    I ended up learning that the very first time an image was insert into my application (whether that be due to a user pressing "take image", "paste image", or "select image", for some reason it insert just fine without auto rotating. At this point, I stored whatever the rotation value was in a global variable called imageOrientationWhenAddedToScreen. This made my life easier because when it came time to manipulate the image and save the image out of the program, I simply checked this cached global variable and determined if I needed to properly rotate the image.

        - (UIImage*) rotateImageAppropriately:(UIImage*) imageToRotate {
        //This method will properly rotate our image, we need to make sure that
        //We call this method everywhere pretty much...
    
        CGImageRef imageRef = [imageToRotate CGImage];
        UIImage* properlyRotatedImage;
    
        if (imageOrientationWhenAddedToScreen == 0) {
           //Don't rotate the image
            properlyRotatedImage = imageToRotate;
    
        } else if (imageOrientationWhenAddedToScreen == 3) {
    
            //We need to rotate the image back to a 3
            properlyRotatedImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:3];
    
        } else if (imageOrientationWhenAddedToScreen == 1) {
    
            //We need to rotate the image back to a 1
            properlyRotatedImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:1];        
    
        }
    
        return properlyRotatedImage;
    
    }
    

    I am still not 100% sure why Apple has this weird image rotation behavior (try this... Take your phone and turn it upside down and take a picture, you'll notice that the final picture turns out right side up - perhaps this is why Apple has this type of functionality?).

    I know I spent a great deal of time figuring this out, so I hope it helps other people!

提交回复
热议问题