Search code examples
swiftimagerotationtransformcrop

Swift - Rotate an image, then zoom in and crop to keep width/height aspect ratio intact


If the title isn't clear, open Photos app on your iPhone and edit a picture. Try the rotation tool. The frame don't rotate, only the image does and zoom in to stay in the frame.

Here is a picture of this:

Rotation photo app tool

I would like to copy this comportment in my Swift project. It means rotating an image (it can be UIImage, CIImage or CGImage) but crop it keeping the same width/height ratio.

Where should I begin ? Thanks for your time.


Solution

  • There's an app a filter for that. CIStraightenFilter rotates an image by any amount while stretching it and cropping it to maintain the original dimensions:

    let image: CIImage = /* my image 480x320 */
    let rotated = image.applyingFilter("CIStraightenFilter", 
        withInputParameters: [ kCIInputAngleKey: Double.pi / 6 ]) // 30 degrees 
    rotated.extent // still 480x320
    

    Here's some examples (rotations of zero, 15°, 30°, and 45°):

    no rotation rotate by π/12 (15 degrees) rotate by π/6 (30 degrees) rotate by π/4 (45 degrees)