Thursday, September 16, 2010

Capturing part of an image from a UIImageView

I have a set of views over a picture and I wanted to pick the part of the picture under the views.  I found some code on stack overflow that helped me extract the part of the photo I wanted, however when I used it, it seemed to be scaled improperly and showed up strangely.

I finally figured out that the reason was because the UIImageView scales the image, and I was using the view coordinates of the part I was interested to try and get the subimage from the picture.  This means that when I'm choosing a number from 0-320 in the view and grabbing those coordinates from a 1200x1600 image.  This meant that I was always in the top left part of the picture.

The following code seems pretty close (it might still be a little off) but at least it grabs stuff in the right vicinity.  I  wanted to solve this problem even though I'm currently planning to actually abandon the 'grab' screen and put on separate dialog approach.  Instead I'm going to create an overlay and place it on top of the current view, allowing precise dynamic changes to occur.

- (UIImage*) getView:(CGRect )area
    if (self.image==nil)
        return nil;
    if (self.image.image==nil)
        return nil;
    // we are using aspect fit, so we will be using which ever is the larger of these two scale factors.
    float widthScaleFactor=self.image.bounds.size.width/self.image.image.size.width;
    float heightScaleFactor=self.image.bounds.size.height/self.image.image.size.height;
    float scaleFactor=widthScaleFactor;
    NSLog(@"scale factors are height=%f width=%f",widthScaleFactor,heightScaleFactor);
    if (widthScaleFactor
    CGRect drawRect=CGRectMake(-area.origin.x/scaleFactor, -area.origin.y/scaleFactor,

    UIImageOrientation currentOrient=self.image.image.imageOrientation;
    CGRect destRect=CGRectMake(0, 0, area.size.width, area.size.height);
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, destRect);
    [self.image.image drawInRect:drawRect];
    UIImage* im=UIGraphicsGetImageFromCurrentImageContext();
    return im;

No comments:

Post a Comment