iOS上文字繪製的幾種方法

2021-09-08 04:14:46 字數 2562 閱讀 1182

文字繪製在開發客戶端程式中是乙個比較常用的功能,可分為採用控制項和直接繪製兩種方式。

採用控制項的方式比較簡便,新增乙個比如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中有這樣一段說明:

.人家說了,如果編碼超出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個示例。

iOS上文字繪製的幾種方法

文字繪製在開發客戶端程式中是乙個比較常用的功能,可分為採用控制項和直接繪製兩種方式。採用控制項的方式比較簡便,新增乙個比如uilabel物件,然後設定相關屬性就好了。但這種方式侷限性也比較大。直接繪製相對比較自由,但也分為使用nsstring和quartz 2d兩種方式。nsstring有一組繪製文...

ios 繪製線框 iOS中畫矩形的幾種方法總結

方法1 pragma mark 畫矩形方法1 void drawrect1 1取得圖形上下文 cgcontextref ctx uigraphicsgetcurrentcontext 2畫一條線段 設定乙個起點 cgcontextmovetopoint ctx,20,20 cgcontextaddl...

文字垂直居中的幾種方法

3 如果上面的 都不生效的話,有可能行內元素是在 裡面,這個時候可以利用inline元素的 css 屬性 vertical align 預設是 baseline 屬性,將其設定為 middle,這個屬性常用於 inline level 和 table cell 的元素。水平垂直居中 拓展 在垂直居中...