4

I have read some posts on this website about using drawInRect instead of the CGContext draw methods. It still draws it upside down? I thought using drawInRect would print it right side up with the coordinate system originating at the top left?

-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
[image drawInRect:CGRectMake(x, size.height-y-height, width, height)];
UIGraphicsPopContext();
}

Notice I'm doing size.height-y-height and if I don't do that it doesn't go where I expect (assuming drawInRect using a topleft coordinate system). It renders in the correct spot with the above code but still upside down. HELP!!!!!!

UPDATE

Thanks to the answer below this is the working method

-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
CGContextSaveGState(context); 
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[image drawInRect:CGRectMake(x, y, width, height)];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}

1 Answer 1

1
    UIGraphicsBeginImageContext(imageViewSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();

// Draw the image in the upper left corner (0,0) with its actual size
CGContextDrawImage(imageContext, imageViewRect, oldImage.CGImage);

//  As it draws the image from lower right corner, 
//  following code will flip it up side down vertically.


CGContextTranslateCTM(imageContext, 0.0, 0.0);
CGContextScaleCTM(imageContext, 1.0, -1.0);

CGContextDrawImage(imageContext, imageViewRect, oldImage.CGImage);
2
  • I'm using stretchableImageWithCapWidth methods on UIImage so I have to use drawInRect to utilize this functionality.
    – Mike S
    Dec 21, 2010 at 4:45
  • Try translating Context first and then use drawInRect,if it works for you. Dec 21, 2010 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.