Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a portion of an image, crop, and save it using Swift?

I am trying to create an iOS app using Swift to capture images and let the user save a selected portion of the image. In many cam based apps, I noticed that a rectangular frame is offered to let the users choose the desired portion. This involves either sliding the edges of the rectangle or moving the corners to fit the required area.

Could you please guide me on how to implement that moveable rectangle and how to save only that piece of the image?

like image 853
Sriram Avatar asked Jul 06 '15 19:07

Sriram


People also ask

How do I crop an image in Swift?

size let xOffset = (sourceSize. width - sideLength) / 2.0 let yOffset = (sourceSize. height - sideLength) / 2.0 // The cropRect is the rect of the image to keep, // in this case centered let cropRect = CGRect( x: xOffset, y: yOffset, width: sideLength, height: sideLength ).

How do I crop a ratio in Swift?

cropping(to: croprect) let cropped = UIImage(cgImage: cr!) context?. draw(cropped, in: rect) let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage!

How do I move an image in Swift?

To move an object, drag it with the mouse. For precise movement, select an object and use the arrow keys.


1 Answers

Using Swift 3

Image cropping can be done using CGImages from CoreGraphics.

Get the CGImage version of a UIImage like this:

// cgImage is an attribute of UIImage
let cgImage = image.cgImage

CGImage objects have a method cropping(to: CGRect) that does the cropping:

let croppedCGImage: CGImage = cgImage.cropping(to: toRect)

Finally, convert back from CGImage to UIImage:

let uiImage = UIImage(cgImage: croppedCGImage)

Example function:

func cropImage(image: UIImage, toRect: CGRect) -> UIImage? {
    // Cropping is available trhough CGGraphics
    let cgImage :CGImage! = image.cgImage
    let croppedCGImage: CGImage! = cgImage.cropping(to: toRect)

    return UIImage(cgImage: croppedCGImage)
}

The CGRect attribute of cropping defines the 'crop rectangle' inside the image that will be cropped.

like image 94
Paulo Avatar answered Sep 18 '22 16:09

Paulo