Unsacrificed
Unsacrificed

Reputation: 189

How to properly draw text with "Core Text" in flipped NSView

I use my own NSView with

- (BOOL) isFlipped { return TRUE; }

to have left-top-based coordinate. The problem is then I draw text with Core Text:

CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, size, NULL);
CFAttributedStringRef attrStr = makeAttrStringRef(str, font);
CTLineRef line = CTLineCreateWithAttributedString(attrStr);
CGContextSetTextPosition(context, pos.x, pos.y); // pos is left-top corener
CTLineDraw(line, context);

the text is flipped:

enter image description here

If I pass flipped matrix to CTFontCreateWithFontDescriptor

CGAffineTransform flipped = (CGAffineTransform){1,0,0,-1,0,0};

the text is shifted (left-top corner of text if not at pos):

enter image description here

What is a proper way to draw text in flipped NSView with keeping left-top-based coordinates?

Upvotes: 0

Views: 944

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

You always must initialize the text matrix before rendering text, typically to identity:

CGContextSetTextMatrix(context, CGAffineTransformIdentity);

It's been a little while, so I can't remember immediately if you need to flip it for a flipped view on macOS. (If you have trouble, add a comment and I'll dredge up the right transform.)

Upvotes: 1

Related Questions