DrawText如何使多行文字居中

(1)DT_WORDBREAK

只能截斷單詞。例如如果輸入一連串英文字符,那麼它會當做一個單詞來處理,而不會自動換行。而對於中文字符則可以。如果要對所有字符都可以像Edit控件中那樣自動換行,那麼可以使用DT_WORDBREAK | DT_EDITCONTROL

 

DT_EDITCONTROL Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.

(2)DT_CALRECT的使用

對於一段text,要計算他的顯示大小,那麼可以使用DT_CALRECT標誌。其中的rect參數屬於IN/OUT類型。輸出時,左上角座標不變,右下角座標改變。函數返回值是文本的高度。當然,它要與不同格式標誌一起使用得到的結果是不一樣的。例如,DT_CALRECT | DT_SINGLELINE 時,它只擴展傳入rect的width,而在多行顯示的時候,即DT_WORDBREAK | DT_WORDBREAK | DT_EDITCONTROL,僅僅擴展height,width不變。

DT_CALCRECT   Determines the width and height of the rectangle. If there are multiple lines of text, DrawText will use the width of the rectangle pointed to by lpRect and extend the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText will modify the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text, but does not draw the text.

(3)DT_CENTER 與 DT_VCENTER

DT_VCENTER只對單行文字的豎直居中有用。DT_CENTER 對單行和多行文字都有用,但只能水平居中。

(4)多行文字的豎直居中

思路:根據顯示中心,重新計算要求的顯示範圍

具體方法:

// ======================================
// = 把str內容顯示到客戶區的中間,但是每行寬度限定爲200,讓其自動換行

CRect clientRect;
   GetClientRect(clientRect); // 獲得客戶區範圍

 

CRect rect;
   rect.left = rect.top = 0;
   rect.right = 200;
   rect.bottom = clientRect.bottom;  // 限定寬度


   CString str = "我是來自非洲的姑娘。心中嚮往神祕的東方,背起行囊尋找夢想,那是龍的故鄉
這裏的人純樸善良,淡淡微笑掛臉龐";


   CRect temp = rect;
   int height = pDC->DrawText(str,temp,DT_CENTER | DT_WORDBREAK | DT_CALCRECT | DT_EDITCONTROL); // 獲得文本高度
 
   rect.DeflateRect(0,(rect.Height() - height) / 2); // 改變rect


   pDC->DrawText(str,rect, DT_CENTER | DT_EDITCONTROL | DT_WORDBREAK);

 


聞香止步 收集於:http://blog.pfan.cn/yuqiexing/40715.html
淘寶店 擺件 飾品 *木雕系列*:海南黃花梨、越南黃花梨、草花梨、小葉紫檀、黑檀、綠檀木、黃楊木、桃木髮簪  木梳 樟木壁掛 佛珠 車飾 擺件

http://shop36570193.taobao.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章