您的位置:首页 > 其它

RichEdit中插入带背景色文本的一种思路

2015-08-21 17:59 309 查看
uses RichEdit;
function TextToRtf( // 将文本处理为RTF格式
mText: WideString // 输入文本
): WideString; // 返回处理后的RTF文本
var
I: Integer;
begin
Result := StringReplace(mText, #13#10, #10, [rfReplaceAll]);
for I := Length(mText) downto 1 do
begin
case mText[I] of
'\':
begin
Delete(Result, I, 1);
Insert('\\', Result, I);
end;
'{':
begin
Delete(Result, I, 1);
Insert('\{', Result, I);
end;
'}':
begin
Delete(Result, I, 1);
Insert('\}', Result, I);
end;
else
if mText[I] > #127 then
begin
Delete(Result, I, 1);
if mText[I] <= #255 then
Insert('\''' + LowerCase(IntToHex(Ord(mText[I]), 2)), Result, I)
else Insert('\u' + IntToStr(Ord(mText[I])) + '?', Result, I);
end;
end;
end;
end;
function InsertColorRtf( // 插入带颜色的RTF文本
mText: string; // 原文本
mRichEdit: TRichEdit; // Rich编辑框
mForegroundColor: TColor; // 前景颜色
mBackgroundColor: TColor; // 背景颜色
mAppendReturn: Boolean = False // 是否追加换行
): Boolean; // 返回插入是否成功
const
cRtfFormat =
'{\rtf1'#13#10 +
'{\colortbl ;\red%d\green%d\blue%d;\red%d\green%d\blue%d;}'#13#10 +
'\cf1\highlight2 %s%s'#13#10 +
'}'#13#10;
begin
Result := False;
if mText = '' then Exit;
if not Assigned(mRichEdit) then Exit;
mForegroundColor := ColorToRGB(mForegroundColor);
mBackgroundColor := ColorToRGB(mBackgroundColor);
SendMessage(mRichEdit.Handle, EM_REPLACESEL, 0,
Longint(PChar(Format(cRtfFormat, [
GetRValue(mForegroundColor),
GetGValue(mForegroundColor),
GetBValue(mForegroundColor),
GetRValue(mBackgroundColor),
GetGValue(mBackgroundColor),
GetBValue(mBackgroundColor),
TextToRtf(mText),
Copy('\par', 1, Ord(mAppendReturn) * 4)
]))));
Result := True;
end; { InsertColorRtf }
procedure TForm1.Button1Click(Sender: TObject);
var
vForegroundColor: TColor;
vBackgroundColor: TColor;
begin
vForegroundColor := Random($FFFFFF);
vBackgroundColor := Random($FFFFFF);
RichEdit1.SelStart := MaxInt;
RichEdit1.SelLength := 0;
InsertColorRtf(Format('%s底%s字', [
ColorToString(vBackgroundColor), ColorToString(vForegroundColor)]),
RichEdit1, vForegroundColor, vBackgroundColor, True);
end;


参考:http://www.cnblogs.com/key-ok/p/3359681.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: