tags:

views:

103

answers:

1

I've recently asked a question about clipping an image via path at view's drawRect method.

http://stackoverflow.com/questions/2570653/iphone-clip-image-with-path

Krasnyk's code is copied below.

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGMutablePathRef path = CGPathCreateMutable();
//or for e.g. CGPathAddRect(path, NULL, CGRectInset([self bounds], 10, 20));
    CGPathAddEllipseInRect(path, NULL, [self bounds]);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGPathRelease(path);
    [[UIImage imageNamed:@"GC.png"] drawInRect:[self bounds]];
}

It works very well. However, when my image is larger than the view itself, how do I show different parts of the image?

I tried tweaking around with translation on the locations (show as bounds above) of ellipse and/or UIImage drawInRect but some complex effects (Unwanted clipping, weird elipse size) I can't explain happens.


EDIT: Maybe I can answer my own question. I can try drawAtPoint instead of drawInRect? Or drawInRect and set the origin to a different location, but expand the size of the rectangle at the same time?

Does that incur performance penalty when I am drawing a larger rectangle than is showing through the view?

+1  A: 

Sounds like you've about figured it out for yourself. drawAtPoint is what you should use. drawInRect will scale the image to fit the destination rect, which is computationally more expensive. Assuming your image is larger than your view, you'll be passing negative x and y values to drawAtPoint in order to clip interior portions of the image.

The example below should display the center portion your image, within your view:

- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
   CGMutablePathRef path = CGPathCreateMutable();
   CGPathAddEllipseInRect(path, NULL, [self bounds]);
   CGContextAddPath(context, path);
   CGContextClip(context);
   CGPathRelease(path);
   UIImage *bigImage = [UIImage imageNamed:@"GC.png"];
   CGPoint topLeftOffset = CGPointMake((self.bounds.size.width - bigImage.size.width) / 2,(self.bounds.size.height - bigImage.size.height) / 2);
   [bigImage drawAtPoint: topLeftOffset];

}

Andy Milburn