Documentation Archive Developer
Search

ADC Home > Reference Library > Technical Q&As > Graphics & Imaging > Quartz >

Why are my Core Graphics calls drawing upside down?


Q: Why are my Core Graphics calls drawing upside down?

A: Unlike the QuickDraw coordinate space, the Core Graphics coordinate space is defined with the positive y-axis pointing up from the lower left corner of the context. This becomes especially disconcerting when you use CreateCGContextForPort to do some CG drawing in a QuickDraw CGrafPort.



//  Create the CGContext from a given QD port
CGContextRef context;
Rect portRect;
OSStatus err = CreateCGContextForPort( qdPort, &context );
if ( noErr == err )
{
    //  Adjust for any SetOrigin calls on qdPort
    SyncCGContextOriginWithPort( context, qdPort );

    //  Move the CG origin to the upper left of the port
    GetPortBounds( qdPort, &portRect );
    CGContextTranslateCTM( context, 0,
            (float)(portRect.bottom - portRect.top) );

    //  Flip the y axis so that positive Y points down
    //  Note that this will cause text drawn with Core Graphics
    //  to draw upside down
    CGContextScaleCTM( context, 1.0, -1.0 );

    //  The CG coordinate space now matches the QD coordinate space
    //  ...
    //  Do your CG drawing here
    //  ...

    //  Release the context now that we are done with it
    CGContextRelease( context );
}
//  Back to normal QuickDraw drawing

Listing 1. Setting up the Core Graphics Context



Luckily, Core Graphics is flexible enough that it allows several solutions. First, you should use SyncCGContextOriginWithPort to update the CG context's origin to account for any SetOrigin calls on the QD port. However, SyncCGContextOriginWithPort does not flip the y-axis for you or move the origin from the bottom left to the top left. For that you have two choices: adjust your drawing yourself to account for the flipped-y and origin difference, or call CGContextTranslateCTM to move the origin and CGContextScaleCTM to flip the y axis for all remaining CG calls in that context.

Listing 1 shows how to set up your CGContext so that you can use Core Graphics calls in a QuickDraw port using the QuickDraw coordinate system.


[Apr 11 2001]