NSImage is making me lose what's left of my hair.

  • My original code using Quartz to render a PDF into a jpeg supported rotations but couldn't zoom in. Thanks to Sven Hoffman, I can now zoom in by using NSImage directly, but now I get a bizarre result when I try to rotate. I've already searched through the list archives, but I can't find anyone whose seen quite this issue:

    1. I have a source image, say 240x320.
    2. I create a target image, 320x240.
    3. I create the NSAffine transform with the translations and rotations as I found in various items in this mail list.
    4. Checking with the debugger, the resulting target image is still 320x240.
    5. I create a bitmap representation using initWithFocusedViewRect.

    6. The size of the resulting image is 240x240?!?

    The worst part is that the resulting image isn't cropped, it's *squashed* - it's been scaled down in the longer direction.

    The first, obvious, possibility is that rotations require square images, but I didn't see that documented anywhere. Can anyone shed any light on this problem?

    Here's the relevant code fragment:

    bmpRect = NSMakeRect(0.0,0.0,bmpSize.width,bmpSize.height);

    if (pdfFileOrientation == PDFFilePortrait) {
      docRect = bmpRect;
    } else {
      docRect = NSMakeRect(0.0,0.0,bmpSize.height,bmpSize.width);
    }

    [bmpImage lockFocus];

    if (landscapeMode) {
      [rot set];
    }

    NSBezierPath *bp = [NSBezierPath bezierPathWithRect:bmpRect];
    [[NSColor whiteColor] set];
    [bp fill];
    [document drawInRect:bmpRect
        fromRect:docRect
        operation:NSCompositeSourceOver
        fraction:1.0];

    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:bmpRect];
    [bmpImage unlockFocus];

    NSData *jpeg = [[bitmap representationUsingType:NSJPEGFileType properties:dict] retain];

    [bitmap release];
  • Transforms apply _after_ drawing operations. So init your bmpImage to
    size bmpRect, but do all your drawing ops (fill, drawInRect) using the
    docRect. For example:

            [document drawInRect:docRect
                                    fromRect:docRect ...

    -Dominic