How to Rotate a UIImage 90 degrees?

前端 未结 19 1226
天涯浪人
天涯浪人 2020-11-22 08:45

I have a UIImage that is UIImageOrientationUp (portrait) that I would like to rotate counter-clockwise by 90 degrees (to landscape). I don\'t want

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 09:11

    I believe the easiest way (and thread safe too) is to do:

    //assume that the image is loaded in landscape mode from disk
    UIImage * landscapeImage = [UIImage imageNamed:imgname];
    UIImage * portraitImage = [[UIImage alloc] initWithCGImage: landscapeImage.CGImage
                                                         scale: 1.0
                                                   orientation: UIImageOrientationRight];
    

    Note: As Brainware said this only modifies the orientation data of the image - the pixel data is untouched. For some applications, this may not be enough.

    Or in Swift:

    guard
        let landscapeImage = UIImage(named: "imgname"),
        let landscapeCGImage = landscapeImage.cgImage
    else { return }
    let portraitImage = UIImage(cgImage: landscapeCGImage, scale: landscapeImage.scale, orientation: .right)
    

提交回复
热议问题