iOS上文本繪制的幾種方法


文本繪制在開發客戶端程序中是一個比較常用的功能,可分為采用控件和直接繪制兩種方式。

采用控件的方式比較簡便,添加一個比如UILabel對象,然后設置相關屬性就好了。但這種方式局限性也比較大。

直接繪制相對比較自由,但也分為使用NSString和Quartz 2D兩種方式。

NSString有一組繪制文本的函數,drawAtPoint是其中一個。使用方式如下:

1 NSString* text = @"This is English text(NSString)."; 2 [text drawAtPoint:CGPointMake(0, 0) withFont:[UIFont systemFontOfSize:20]];

接口還是比較簡單的,也可以畫中文。

1 text = @"這是中文文本(NSString)。"; 2 [text drawAtPoint:CGPointMake(0, 50) withFont:[UIFont systemFontOfSize:20]];

Quartz 2D中文本繪制稍微復雜一點,因為它提供的接口是C形式的,而不是OC的。先來看看如何畫英文:

1 CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, -1.0)); 2 CGContextSelectFont(context, "Helvetica", 20, kCGEncodingMacRoman); 3 const char* str = "This is English text(Quartz 2D)."; 4 CGContextShowTextAtPoint(context, 0, 100, str, strlen(str));

CGContextSetTextMatrix是調整坐標系,防止文字倒立。
我們用同樣的方法嘗試繪制中文。

1 const char* str1 = "這是中文文本(Quartz 2D)。"; 2 CGContextShowTextAtPoint(context, 0, 150, str1, strlen(str1));

但屏幕上顯示的是亂碼。為什么呢?

Quartz 2D Programming Guide中有這樣一段說明:

To set the font to a text encoding other than MacRoman, you can use the functions CGContextSetFont and CGContextSetFontSize. You must supply a CGFont object to the function CGContextSetFont. You call the function CGFontCreateWithPlatformFont to obtain a CGFont object from an ATS font. When you are ready to draw the text, you use the function CGContextShowGlyphsAtPoint rather than CGContextShowTextAtPoint.

人家說了,如果編碼超出MacRoman的范圍,你要使用CGContextShowGlyphsAtPoint來繪制。這個函數和CGContextShowTextAtPoint類似,也是5個參數,而且只有第四個參數不同,是字形數組(可能描述的不准確)CGGlyph glyphs[],這個東西如何得到呢?在CoreText frameork(support iOS3.2 and later)提供了這樣的接口。代碼如下:

復制代碼
 1 UniChar *characters;  2 CGGlyph *glyphs;  3 CFIndex count;  4  5 CTFontRef ctFont = CTFontCreateWithName(CFSTR("STHeitiSC-Light"), 20.0, NULL);  6 CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(ctFont);  7 CGFontRef cgFont = CTFontCopyGraphicsFont(ctFont,&ctFontDesRef );  8 CGContextSetFont(context, cgFont);  9 CFNumberRef pointSizeRef = (CFNumberRef)CTFontDescriptorCopyAttribute(ctFontDesRef,kCTFontSizeAttribute); 10 CGFloat fontSize; 11 CFNumberGetValue(pointSizeRef, kCFNumberCGFloatType,&fontSize); 12 CGContextSetFontSize(context, fontSize); 13 NSString* str2 = @"這是中文文本(Quartz 2D)。"; 14 count = CFStringGetLength((CFStringRef)str2); 15 characters = (UniChar *)malloc(sizeof(UniChar) * count); 16 glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * count); 17 CFStringGetCharacters((CFStringRef)str2, CFRangeMake(0, count), characters); 18 CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, count); 19 CGContextShowGlyphsAtPoint(context, 0, 200, glyphs, str2.length); 20 21 free(characters); 22 free(glyphs);
復制代碼

STHeitiSC-Light是系統自帶的一種中文字體。

這樣寫的話中文就能正常繪制出來了。

下圖是顯示效果,分別對應上面的5個示例。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM