PDA

View Full Version : Capture UIImage with offset into UIScrollView




justinjas
Jan 7, 2009, 11:00 PM
I have an app that displays a large horizontal UIScrollView to allow the user to swipe through multiple images that are all 320x480. I need to be able to capture a UIImage with a certain offset into the UIScrollView. Here is what I have so far where scrollView is my UIScrollView:

UIGraphicsBeginImageContext(scrollView.bounds.size);
[scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This works but only captures the first 320x480 section of the scrollView. What I really want to capture is the section that is located at (320*currentPage, 0, 320, 480) so the offset starts at the current page.

I tried code like this:

CGSize pageSize = CGSizeMake(320 * currentPage, 480);
UIGraphicsBeginImageContext(pageSize);
....

But ended up with an image that contained all the images side by side in a low resolution. The problem is that I don't really understand the way ImageContext works and it would seem that you can only set a size for them and not an offset and size.

Any help would be appreciated. Thanks.



justinjas
Jan 19, 2009, 01:31 AM
I came back to this issue tonight, here was the solution that worked for me using CGContextTranslateCTM to move into the offset I needed.

CGSize pageSize = CGSizeMake(320, 480);
UIGraphicsBeginImageContext(pageSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(resizedContext, 320 * -currentPage, 0);
[scrollView.layer renderInContext:resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();