6

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?

thomasdao
  • 972
  • 12
  • 26

2 Answers2

15

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;
    }
iPatel
  • 46,010
  • 16
  • 115
  • 137
0

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];


}
Dhara
  • 4,093
  • 2
  • 36
  • 69
  • Your `imageRef` is going to leak memory, you need `CGImageRelease(imageRef);` at the end – WDUK Jan 28 '13 at 20:58
  • ARC does not apply to CGImageRef. By the end, I mean before you return `UIImage`. – WDUK Jan 29 '13 at 09:35