Crop Image Bottom Programmatically

I am working on a custom camera application. Everything works well.

But I got into a problem by cropping the image from below. that is, the cropped image has the same width as the original image, but the height will be 1/3 of the original image, and it should start from the bottom.

Example For example, this is a full image, I only need the red part

+6
source share
4 answers

Swift 3 solution:

func cropBottomImage(image: UIImage) -> UIImage { let height = CGFloat(image.size.height / 3) let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height) return cropImage(image: image, toRect: rect) } 

A helper method for cropping with a rectangle:

 func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{ let imageRef:CGImage = image.cgImage!.cropping(to: rect)! let croppedImage:UIImage = UIImage(cgImage:imageRef) return croppedImage } 
+17
source

this is almost the answer Alexburtnik

but just mention that UIImage.size is a logical size (in “dots”)

however, CGImage.cropping () used the actual measurement (in pixels)

therefore, if you use an image with @ 2x or @ 3x modifiers, you will find the cropping is actually half or a third of the expected result.

so when you crop, you might first consider multiplying the rectangle with the "scale" property of the image, for example the following:

 func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? { var rect = rect rect.size.width = rect.width * image.scale rect.size.height = rect.height * image.scale guard let imageRef = image.cgImage?.cropping(to: rect) else { return nil } let croppedImage = UIImage(cgImage:imageRef) return croppedImage } 
+7
source

Method:

 func croppIngimage(ImageCrop:UIImage, toRect rect:CGRect) -> UIImage{ var imageRef:CGImageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, rect) var croppedimage:UIImage = UIImage(CGImage:imageRef) return croppedimage } 

Call:

 var ImageCrop:UIImage = UIImage(named:"image.png") 
0
source

As an extension for UIImage:

 import UIKit extension UIImage { func crop(to rect: CGRect) -> UIImage? { // Modify the rect based on the scale of the image var rect = rect rect.size.width = rect.size.width * self.scale rect.size.height = rect.size.height * self.scale // Crop the image guard let imageRef = self.cgImage?.cropping(to: rect) else { return nil } return UIImage(cgImage: imageRef) } } 

Using:

 let myImage = UIImage(named:"myImage.png") let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight) let croppedImage = myImage.crop(to: croppedRect) 
0
source