views:

191

answers:

3

Code sample

- (void)drawRect:(CGRect)rect {  
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, self.frame.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height), [UIImage imageNamed:@"sample.png"].CGImage);

    CGContextRestoreGState(context);    
}

================

I would like to copy a certain rect within an image to the context, so not the entire image is drawn but just a piece of the image. Does anyone have a solution for this? I can't find anything on google nor the documentation.

I know there are alternatives like: 1. Create a UIView with clipping and then just position the UIImageView within it. 2. Create the UIImageView within the UIScrollView and use content offset.

But I think those are lame...

+1  A: 

You could try CGImageCreateWithImageInRect

adam
nope that didnt work thanks for your effort though
Mark
Hi Mark, please see James' response below. CGImageCreateWithImageInRect will work, it's a slightly tidier way of achieving the crop as you achieved below.
adam
A: 

This did work:

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

CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);

CGRect drawRect = CGRectMake(rect.origin.x * -1,
                             rect.origin.y * -1,
                             imageToCrop.size.width,
                             imageToCrop.size.height);

CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
Mark
your solution seems to be overcomplicating a simple task - adam and James are pointing into the right direction
Till
+2  A: 

CGImageCreateWithImageInRect should work fine. That's how I do it. Here's an example:

CGImageRef ref = CGImageCreateWithImageInRect(some_UIImage.CGImage, CGRectMake(x, y, height, width));
UIImage *img = [UIImage imageWithCGImage:ref];

This example gets a CGImageRef from the CGImage property of another_UIImage, an instance of UIImage, then crops it, and turns it back into a UIImage with UIImage's imageWithCGImage constructor method. Good luck!

James

James