Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flip coordinates when drawing in context?

I create a context from an UIImage, and then I draw into it with

CGContextDrawImage(bitmapContext,
                   CGRectMake(0, 0,
                              originalImage.size.width,
                              originalImage.size.height),
                   oImageRef); 

the image appears upside-down due to the flipped coordinate system in quartz. How can I fix that?

like image 233
Thanks Avatar asked Jul 17 '09 20:07

Thanks


2 Answers

You should be able to transform the context using something similar to the following:

CGContextSaveGState(bitmapContext);
CGContextTranslateCTM(bitmapContext, 0.0f, originalImage.size.height);
CGContextScaleCTM(bitmapContext, 1.0f, -1.0f);

// Draw here
CGContextDrawImage(bitmapContext, CGRectMake(0, 0, originalImage.size.width, originalImage.size.height), oImageRef);

CGContextRestoreGState(bitmapContext);

The translation may not be necessary for the image drawing, but I needed it when I wanted to draw inverted text. If this is the only thing you'll be doing in the context, you might also be able to get rid of the calls to save and restore the context's state.

like image 81
Brad Larson Avatar answered Nov 01 '22 23:11

Brad Larson


Brad's solution as an extension in Swift 3:

extension CGContext {
    func drawFlipped(image: CGImage, rect: CGRect) {
        saveGState()
        translateBy(x: 0, y: rect.height)
        scaleBy(x: 1, y: -1)
        draw(image, in: rect)
        restoreGState()
    }
}
like image 29
user3717478 Avatar answered Nov 02 '22 00:11

user3717478