---
title: "DrawText 使用"
author: "guowee"
date: "2010-04-12T16:37:55Z"
tags: []
categories: ["编程语言"]
slug: "drawtext"
draft: false
lastmod: "2010-04-12T16:37:55Z"
id: 641985
url: "https://guowee.iteye.com/blog/641985"
---

（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-&gt;DrawText(str,temp,DT\_CENTER | DT\_WORDBREAK | DT\_CALCRECT | DT\_EDITCONTROL); // 获得文本高度  
   
   rect.DeflateRect(0,(rect.Height() - height) / 2); // 改变rect

   pDC-&gt;DrawText(str,rect, DT\_CENTER | DT\_EDITCONTROL | DT\_WORDBREAK);