How to rotate UIImage

后端 未结 10 729
既然无缘
既然无缘 2021-01-03 23:03

I\'m developing an iOS app for iPad. Is there any way to rotate a UIImage 90º and then add it to a UIImageView? I\'ve tried a lot of different codes but none worked...

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 23:45

    To rotate the pixels you can use the following. This creates an intermediate UIImage with rotated metadata and renders it into a image context with width/height dimensions transposed. The resulting image has the pixels rotated (i.e the underlying CGImage)

    - (UIImage*)rotateUIImage:(UIImage*)sourceImage clockwise:(BOOL)clockwise
    {
        CGSize size = sourceImage.size;
        UIGraphicsBeginImageContext(CGSizeMake(size.height, size.width));
        [[UIImage imageWithCGImage:[sourceImage CGImage] scale:1.0 orientation:clockwise ? UIImageOrientationRight : UIImageOrientationLeft] drawInRect:CGRectMake(0,0,size.height ,size.width)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    There are other possible values that can be passed for the orientation parameter to achieve 180 degree rotation and flips etc.

提交回复
热议问题