本文介绍了Delphi - 在rect的中心绘制文本多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Delphi中,我希望在TRect中绘制文本。我希望以下功能:
In Delphi i wish to draw text inside a TRect. I am hoping for the following functionality:
- 在TRect 中绘制垂直居中的文本
- 绘制文本在TRect
- 中间水平放置文本如果空格超过1行文本(使用TRect的高度),则绘制文本多行
- 如果文本不符合TRect(单行或多行),则将省略号添加到文本。
- Draw the text centred vertically within the TRect
- Draw the text centred horizontally within the TRect
- If there is space for more than 1 line of text (using TRect's height), draw the text multiline
- If the text does not fit in the TRect (either on a single or mult line) then append ellipsis to the text.
我可以看到Windows.DrawText()函数几乎涵盖了这个功能,但是当写入文本,多行和垂直居中是相互排斥的。
I can see the Windows.DrawText() function almost covers this functionality, however when writing text, multiline and vertically centred are mutually exclusive.
我是想知道这个功能是否内置到Windows(2000+)?如果没有这样做,而不用写我自己的功能?
I was wondering if this functionality is built into windows (2000+)? If not is there a way to do this without writing my own function?
推荐答案
对不起,这是所有以前的答案的组合和评论。但是似乎OP需要更多的帮助。
Sorry, this is a combination of all previous answers and comments. But it seems OP needs more assistance.
function DrawTextCentered(Canvas: TCanvas; const R: TRect; S: String): Integer;
var
DrawRect: TRect;
DrawFlags: Cardinal;
DrawParams: TDrawTextParams;
begin
DrawRect := R;
DrawFlags := DT_END_ELLIPSIS or DT_NOPREFIX or DT_WORDBREAK or
DT_EDITCONTROL or DT_CENTER;
DrawText(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags or DT_CALCRECT);
DrawRect.Right := R.Right;
if DrawRect.Bottom < R.Bottom then
OffsetRect(DrawRect, 0, (R.Bottom - DrawRect.Bottom) div 2)
else
DrawRect.Bottom := R.Bottom;
ZeroMemory(@DrawParams, SizeOf(DrawParams));
DrawParams.cbSize := SizeOf(DrawParams);
DrawTextEx(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags, @DrawParams);
Result := DrawParams.uiLengthDrawn;
end;
procedure TForm1.FormPaint(Sender: TObject);
const
S = 'This is a very long text as test case for my paint routine.';
var
R: TRect;
begin
SetRect(R, 100, 100, 200, 140);
Canvas.Rectangle(R);
InflateRect(R, -1, -1);
Caption := Format('%d characters drawn', [DrawTextCentered(Canvas, R, S)]);
end;
这篇关于Delphi - 在rect的中心绘制文本多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!