How to Display International Accents with Quartz/C

2019-05-24 11:43发布

问题:

I've localized an app for the iPhone. No surprise, the localization includes some accents:

"Touch cards to select. Then touch 'Bid'." = "Touchez les cartes pour les sélectionner, puis touchez 'Miser'.";

These work fine in high-level stuff, like when I put the text into a table, but when I try to write them to a UIView by hand, the accents get mangled:

I'm using kCGEncodingMacRoman and UTF8, both of which should support accents, I think, but I'm clearly missing something:

CGContextSelectFont(ctx,fontName,thisWriting.fontSize,kCGEncodingMacRoman);
CGContextShowTextAtPoint(ctx,
                        thisWriting.center.x - floor(thisTextSize.width/2),
                        yThusFar,
                        [thisText UTF8String],
                        [thisText length]);

The font is some variant of ArialMT. thisText is just an NSString.

回答1:

Quartz provides a limited, low-level interface for drawing text. For information on text-drawing functions, see CGContext Reference. For full Unicode and text-layout support, use the services provided by Core Text or ATSUI).



回答2:

To expand on what sorin said: Quartz/Core Graphics do not support Unicode text, which includes the accents you need for foreign languages. There have traditionally been a number of alternative ways to resolve this, but currently the best answer is to use Core Text, which can write directly to a graphical context, as I was doing here.

The main element in Core Text is the NSAttributedString or NSMutableAttributed String class.

Here's similar code to what I had for Core Text:

CTLineRef thisLine = CTLineCreateWithAttributedString((CFAttributedStringRef)thisAText);
CGContextSetTextPosition(ctx, self.center.x - floor(thisTextSize.width/2), yThusFar);
CTLineDraw(thisLine, ctx);

The font is already taken care of, because it's part of that NSAttributedString (or CFAttributedStringRef, which is a toll-free bridged equivalent).

Here's the result: