Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS how to draw a part of image to a specific rect?

I want to crop a 200*200 image, the cropped part is (x=10,y=10,w=50,h=50). and drawing this part to new 500*500 image, the new rect is (x=30,y=30,w=50, h=50), how to do it?

I can get the part of image with the following method

- (UIImage*) getSubImageWithRect: (CGRect) rect {

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translated rectangle for drawing sub image
    CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, self.size.width, self.size.height);

    // clip to the bounds of the image context
    // not strictly necessary as it will get clipped anyway?
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));

    // draw image
    [self drawInRect:drawRect];
    // grab image
    UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return subImage;
}
like image 532
NOrder Avatar asked Oct 11 '25 17:10

NOrder


1 Answers

Lets try using following code chunk

- (UIImage*) getSubImageFromImage:(UIImage *)image
{
      // translated rectangle for drawing sub image
      CGRect drawRect = CGRectMake(10, 10, 50, 50);
      // Create Image Ref on Image
      CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
      // Get Cropped Image
      UIImage *img = [UIImage imageWithCGImage:imageRef];
      CGImageRelease(imageRef);
      return img;
}