How to get UIImage of a specific area in current ios screen

The following code gets the UIImage of the current screen:

UIGraphicsBeginImageContext(self.view.frame.size); CGContextRef ctx = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:ctx]; UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

If I have a CGRect rect, and I want to get only the UIImage of the current screen in this rectangle, how can I do this?

+6
source share
2 answers

To obtain a Rect (Crop) image:

 UIImage *croppedImg = nil; CGRect cropRect = CGRectMake(AS You Need); croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect]; 

Use the following method returning UIImage (since you want the image size)

 - (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect { //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15); CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect); UIImage *cropped = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return cropped; } 
+14
source

Transfer the image you want to crop and change image.size.width and image.size.height according to your requirement

 -(UIImage *)cropSquareImage:(UIImage *)image { CGRect cropRect; if (image.size.width < image.size.height) { float x = 0; float y = (image.size.height/2) - (image.size.width/2); cropRect = CGRectMake(x, y, image.size.width, image.size.width); } else { float x = (image.size.width/2) - (image.size.height/2); float y = 0; cropRect = CGRectMake(x, y, image.size.height, image.size.height); } CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect); return [UIImage imageWithCGImage:imageRef]; } 
0
source

All Articles