coreText繪製文字

2021-08-21 23:59:10 字數 2433 閱讀 9437

為了使**結構清晰,可以將配置文字屬性(包括字型大小,行間距等資訊)寫成乙個類,再用乙個類去排版布局文字,最後將排版好的文字繪製在view上。

首先根據要顯示的文字以及文字屬性生成nsmutableattributedstring

//content就是要顯示的文字內容

nsmutableattributedstring *attstring = [[nsmutableattributedstring alloc] initwithstring:content];

//config是用來記錄文字屬性(包括字型大小,字型顏色等資訊)的類的物件

nsmutabledictionary *dict = [nsmutabledictionary dictionary];

//記錄字型大小

dict[nsfontattributename] = [uifont systemfontofsize:config.fontsize];

//字型顏色

dict[nsforegroundcolorattributename] = config.fontcolor;

//行間距

nsmutableparagraphstyle *style = [[nsmutableparagraphstyle alloc] init];

style.linespacing = config.linespace;

style.alignment = nstextalignmentjustified;

dict[nsparagraphstyleattributename] = style;

//設定屬性以及文字內容(也可以分別設定字型大小,字型顏色等屬性)

[attstring addattributes:dict range:nsmakerange(0, content.length)];

//兩個引數分別是文字屬性、該文字屬性約束的文字範圍

//這裡將整個文字(nsmakerange(0, content.length))設定成了同一種樣式,我們也可以根據自己的需求分別設定每一段的字型樣式,也可以加下劃線,字型加粗等。

根據文字以及文字屬性配置ctframesetterref

ctframesetterref setterref = ctframesettercreatewithattributedstring((__bridge cfattributedstringref)attstring);
注:這裡需要將oc物件轉為cf物件,__bridge表示在將oc物件轉為cf物件時不涉及物件轉換,所以轉換後不需要手動釋放attstring  

設定繪製區域,並根據繪製區域和ctframesetterref生成ctframeref

//文字要布局顯示的區域

cgpathref pathref = cgpathcreatewithrect(bounds, null);

//將cfrangemake(0, 0)length設為0布局會根據ctframesetterref在pathref區域內一直排版直到排滿

ctframeref frameref = ctframesettercreateframe(setterref, cfrangemake(0, 0), pathref, null);

//第乙個引數是待排版的ctframesetterref,第二個引數是排版的文字範圍,第三個引數是排版區域。

cfrelease(setterref);

cfrelease(pathref);

注:arc環境下編譯器不會自動管理cf物件的記憶體,需要手動釋放

以上內容寫在乙個用於排版的類(生成ctframeref)中,通過這個類獲取到 ctframeref後,在view裡重寫drawrect方法,將布局好的文字繪製到view上

- (void)drawrect:(cgrect)rect

//翻轉座標系

cgcontextref ctx = uigraphicsgetcurrentcontext();

cgcontextsettextmatrix(ctx, cgaffinetransformidentity);

cgcontexttranslatectm(ctx, 0, self.bounds.size.height);

cgcontextscalectm(ctx, 1.0, -1.0);

//繪製到view

ctframedraw(_frameref, ctx);

}

注:coretext座標系和uikit座標系的不同,繪製之前我們需要將座標系統一; _frameref不會自動釋放,我們必須要手動釋放掉。

-(void)setframeref:(ctframeref)frameref

_frameref = frameref;

}}-(void)dealloc

}

IOS利用Core Text對文字進行排版

2011 12 08 11 10 core text 這個包預設是沒有的,要自己手動新增進來。在ios中利用core text對文字進行排版的幾個關鍵點如下 字間距 kctkernattributename 行間距 kctparagraphstylespecifierlinespacingadjus...

CoreText 學習記錄

基於swift 4.0.一 座標系 coretext 的原點是左下角。而進行ui布局時參照的座標系原點在左上角。所以一般會對座標系進行翻轉。在override func draw rect cgrect 中呼叫 coretext 設定前10個字為紅色帶下劃線 func test01 1.let co...

QT文字繪製

1 基本繪製 qpainter painter this 這個this要斟酌下 painter.drawtext 100,100,yafeilinux 2 中級繪製 qpainter painter this qrectf ff 100,100,300,200 設定乙個矩形 painter.draw...