Reputation: 982
The following code get 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 that rect, how can I do?
Upvotes: 6
Views: 3609
Reputation: 47069
For Get Rect (Crop) Image:
UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS You Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
Use following method that return UIImage
(as You want size of image)
- (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;
}
Upvotes: 15
Reputation: 4089
Pass the image which you want to be cropped and change the image.size.width and image.size.height as per 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];
}
Upvotes: 0