Search code examples
swiftuiimageviewuiimage

How to crop UIImage freely in swift?


I am working on uiimage, on which i need to add a crop image functionality, like shown in imageenter image description here

How can i do that? I don't want to use third party library for this.


Solution

  • Assuming you know how to display the UIimage, how to draw the crop rectangle on top of the image, and how to allow the user to modify that crop rectangle, then the actual cropping could be done via CGImage's cropping(to:) function documented here:

    https://developer.apple.com/documentation/coregraphics/cgimage/1454683-cropping

    There's a nice bit of sample code in the documentation for cropping(to:) at that link that implements a cropImage function in Swift that uses cropping(to:).

    Get the CGImage from the UIImage via the cgImage property on UIImage.