参考我这段代码,效率可能不是很高 []
procedure DrawCanvasText(Canvas: TCanvas;
Rect: TRect;
Str: String;
BkColor: TColor;
TabWidth: Integer = 8);
var
i, j: Integer;
tmpStr, tmpStr1: String;
sX,sY: Integer;
Len: Integer;
WriteEnable: Boolean;
begin
if Str='' then
Exit;
Str:=StringReplace(Str,#13#10,#13,[rfReplaceAll]);
if RightStr(Str,1)<>#13 then
Str:=Str+#13;
with Rect,Canvasdo
begin
Brush.Style:=bsSolid;
Brush.Color:=BkColor;
FillRect(Rect);
Brush.Style:=bsClear;
sY:=Top;
Len:=Length(Str);
WriteEnable:=False;
i:=0;
while(i<=Len)do
begin
Inc(i);
if Str=#13 then
WriteEnable:=True
else
begin
if Str=#9 then
tmpStr:=tmpStr+StringOfChar(' ',TabWidth)
else
begin
tmpStr:=tmpStr+Str;
if Byte(Str)>=$A0 then
begin
tmpStr:=tmpStr+Str[i+1];
Inc(i);
end;
end;
if (TextWidth(tmpStr)>Right-Left) and (not (Str in [#9,' '])) then
begin
WriteEnable:=True;
if tmpStr[Length(tmpStr)]>=Char($A0) then
begin
tmpStr1:=Copy(tmpStr,Length(tmpStr)-1,2);
tmpStr:=Copy(tmpStr,1,Length(tmpStr)-2);
end
else
begin
for j:=Length(tmpStr)-1do
wnto 1do
begin
if (tmpStr[j]=' ') or (tmpStr[j]>=Char($A0)) then
begin
tmpStr1:=Copy(tmpStr,j+1,Length(tmpStr)-j);
tmpStr:=Copy(tmpStr,1,j);
break;
end;
end;
if j=0 then
begin
tmpStr1:=Str;
tmpStr:=Copy(tmpStr,1,Length(tmpStr)-1);
end;
end;
end;
end;
if WriteEnable then
begin
WriteEnable:=False;
if (sY+TextHeight(tmpStr+' ')>Bottom) then
Exit;
sX:=Left;
if tmpStr<>'' then
TextRect(Rect,sX,sY,tmpStr);
sY:=sY+TextHeight(tmpStr+' ');
if tmpStr1<>'' then
begin
tmpStr:=tmpStr1;
tmpStr1:='';
end
else
tmpStr:='';
end
end;
end;
end;