Question

I have written a simple Cocoa app for Mac OS X (10.7) using Xcode 4.2. All the app does is create a window with a scrollable array of sub-Views in it, each representing a page to draw stuff on at a very low level. The sub-View's isFlipped method delivers YES, so the origin of every sub-View is the upper left corner. Using various Core Graphics routines, I'm able to draw lines and fill paths and all that fun PostScripty stuff successfully.

It's drawing glyphs from a given font that's got me confused.

Here's the complete code, cut-n-pasted from the program, for the sub-View's -drawRect: method --

- (void)drawRect:(NSRect)dirtyRect
{
  // Start with background color for any part of this view
  [[NSColor whiteColor] set];
  NSRectFill( dirtyRect );

  // Drop down to Core Graphics world, ensuring there's no side-effects
  context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  CGContextSaveGState(context);
  {
    //CGFontRef theFont = CGFontCreateWithFontName(CFSTR("American Typewriter"));
    //CGContextSetFont(context, theFont);
    CGContextSelectFont(context, "American Typewriter", 200, kCGEncodingMacRoman);
    CGContextSetFontSize(context, 200);

    // Adjust the text transform so the text doesn't draw upside down
    CGContextSetTextMatrix(context, CGAffineTransformScale(CGAffineTransformIdentity, 1, -1));

    CGContextSetTextDrawingMode(context, kCGTextFillStroke);
    CGContextSetRGBFillColor(context, 0.0, .3, 0.8, 1.0);

    // Find the center of view's (not dirtyRect's) bounds
    // View is 612 x 792 (nominally 8.5" by 11")

    CGPoint centerPoint;
    CGRect bds = [self bounds];
    centerPoint.x = bds.origin.x + bds.size.width  / 2;
    centerPoint.y = bds.origin.y + bds.size.height / 2;

    // Create arrays to hold glyph IDs and the positions at which to draw them.
    #define glyphCount 1                        // For now, just one glyph
    CGGlyph glyphs[glyphCount];
    CGPoint positions[glyphCount];

    glyphs[0] = 40;                             // Glyph ID for '@' character in above font
    positions[0] = centerPoint;

    // Draw above center.  This works.
    CGContextShowGlyphsAtPoint(context, centerPoint.x, centerPoint.y - 200.0, glyphs, glyphCount);

    // Draw at center.  This works.
    CGContextShowGlyphsAtPoint(context, positions[0].x, positions[0].y, glyphs, glyphCount);

    // Draw below center.  This fails (draws nothing).  Why?
    positions[0].y += 200.0;
    CGContextShowGlyphsAtPositions(context, glyphs, positions, glyphCount);
  }
  CGContextRestoreGState(context);
}

What's got me pulling my hair out is that the first two glyph-drawing calls using CGContextShowGlyphsAtPoint() work fine as expected, but the third attempt using CGContextShowGlyphsAtPositions() never draws anything. So there are only two @ symbols on the page, rather than three. This difference in behaviors doesn't depend on whether I've previously used CGContextSetFont() or CGContextSelectFont().

There must be some hidden change in state going on, or something very different under the hood w/r/t these two almost identical Core Graphics glyph-drawing routines, but all my experiments so far have not demonstrated what that might be.

Sigh. I just want to efficiently draw an array of glyphs at a corresponding array of positions in a view.

Any ideas what I'm getting wrong?

Was it helpful?

Solution

After much experimentation enabled by being whacked upside the head by Peter Hosey's response (even though some of it isn't quite right, many thanks!), here's the source of my confusion and an explanation I'm pretty sure is correct (well, the code is doing what I expect it to, anyway).

In the usual higher-level PostScript path/drawing model, drawing a character updates the current point (path end) to the position where a next character might appear, leaving the current user-space transform the same. But under the hood, the text matrix transform is translated by the glyph's width (or more accurately by an advance vector) so that the next character to be drawn can start at, or with respect to, a new text origin. The text matrix's scale factors remain unchanged after translation.

So the initial setup call to CGContextSetTextMatrix() to flip the vertical sense of the text matrix is still necessary (if user-space is similarly flipped), because otherwise both glyph-collection drawing routines will draw the glyphs upside-down w/r/t path drawing, no matter where the text drawing starts or which drawing routine is used.

Neither of the two glyph collection drawing routines affects the current path. They are lower-level than that. I found that I could intersperse either routine among path construction calls without affecting a path's position or shape.

In the code posted above, the position data that CGContextShowGlyphsAtPositions() uses to draw the glyph collection are all relative to the user-space point corresponding to the current text matrix's origin, which was translated to the right of the previously drawn '@' glyph. Because I was using such a large font size, position[0] was causing the next '@' glyph to be drawn outside the view's bounds, so it wasn't visible, but it was being drawn.

But there's still some nuances among the two routines. CGContextShowGlyphsAtPositions() can never be used to place glyphs at any absolute user-space position. So how do you tell it where to start? The answer (or at least one answer) is that CGContextShowGlyphsAtPoint() updates the origin of the text matrix to the given user-space point even if there are no glyphs to draw. And CGContextShowGlyphsAtPoint() must translate the text matrix after each glyph it draws, because what would be the point (so to speak) of drawing the entire glyph collection on top of one another.

So one can "move" to a non-path point in user-space using CGContextShowGlyphsAtPoint() with a glyph count of 0, and then one can call CGContextShowGlyphsAtPositions() (any number of times) with a vector of positions each of which will be treated relative to the text matrix's origin (or really, the user-space point corresponding to it) without the text matrix origin being updated at all when CGContextShowGlyphsAtPositions() returns.

Finally, note that the position data provided to CGContextShowGlyphsAtPositions() is in user-space coordinates. A comment in Apple's header file for these routines expressly says so.

OTHER TIPS

One possibility is this, from the CGContextShowGlyphsAtPositions document:

The position of each glyph is specified in text space, and, as a consequence, is transformed through the text matrix to user space.

The text matrix is a separate property of the context, distinct from the graphics state's current transformation matrix.

It doesn't say that about CGContextShowGlyphsAtPoint:

This function displays an array of glyphs at the specified position in the user space.

(Emphasis added to both quotes.)

So, your text matrix is not actually used when you show glyphs from a single point.

But then, when you show glyphs at an array of positions, it is used, and you see the symptom of a wrong matrix. Specifically, your matrix to try to flip the text back the other way is wrong: it flips the coordinate system upside down. You are drawing outside of the view.

(Try setting it to scale by 0.5 instead of -1 and you'll see what I mean.)

My recommendation is to take out your CGContextSetTextMatrix call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top