Search code examples
iphoneiosobjective-cimagecgcontext

CGBitmapContextCreateImage on flipped context


I've got a context, on which i've performed some drawing. Now i want to save a result. Because of inverted context y-axis first i want to flip everything, then create image:

// 1. Flip Y
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);

// 2. Create image
CGImageRef rawMask = CGBitmapContextCreateImage(context);

However the image is not flipped. Even if i change the order of action 1 with 2, the image still is not flipped. I can't understand why and how to fix it. More important is 'why', because in my logic, if i flip the context with upside down drawing, it should be ok.


Solution

  • The CTM affects the drawing operations you perform after you set the CTM. That is to say, changing the CTM can change which pixels are modified by your subsequent drawing operations.

    The CTM does not affect CGBitmapContextCreateImage directly. CGBitmapContextCreateImage simply copies the pixels out of the context into an image. It doesn't look at the CTM at all.

    Thus you have omitted a critical part of your program from your question: the part that actually modifies the pixels. The correct order is this:

    // 1. Flip Y axis.
    CGContextTranslateCTM(context, 0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    // 2. Draw into context.  For example:
    CGContextBeginPath(context);
    CGContextAddEllipseInRect(context, someRect);
    CGContextSetFillColorWithColor(context, ...);
    CGContextFillPath(context);
    
    // 3. Create image.
    CGImageRef rawMask = CGBitmapContextCreateImage(context);