3

I'm working in a function for scaling and crop image (similar to camara app) for iOS, the code below works fine, just that the resulting image came up side down, and I would like to understand why.

Thanks

- (UIImage*)imageByCropping:(UIImageView *)imageViewToCrop toRect:(CGRect)rect
{
    //create a context to do our clipping in
    CGRect newRect = CGRectApplyAffineTransform(rect, imageViewToCrop.transform);
    UIImage *imageToCrop = imageViewToCrop.image;
    UIGraphicsBeginImageContext(newRect.size);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    //create a rect with the size we want to crop the image to
    //the X and Y here are zero so we start at the beginning of our
    //newly created context
    CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
    CGContextClipToRect( currentContext, clippedRect);


    //draw the image to our clipped context using our offset rect
    CGContextDrawImage(currentContext, newRect, imageToCrop.CGImage);

    //pull the image from our cropped context
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return cropped;

} 
Anjali Kevadiya
  • 3,567
  • 4
  • 22
  • 43
Marco
  • 31
  • 3

1 Answers1

0

I've also came across this issue without explanation. But have found a workaround that solves that problem. Just put the following two lines in your code and try it again. It works for me.

CGContextTranslateCTM(context, 0.0, newRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context
Borut Tomazin
  • 8,041
  • 11
  • 78
  • 91