使用已加载的文本独立更改 RichEdit 文本颜色
Change RichEdit text colour independently with text already loaded
如何逐行更改 Rich Edit 的文本颜色?这取决于位置。第一行必须是红色,第二行必须是绿色等等。问题是 Rich Edit 的文本已经载入。因此必须在文本已经在控件中后更改它。我正在使用 Delphi.
最好从一开始就加载正确的颜色。
但要回答你的问题,一个快速、肮脏且相当丑陋的解决方案是
function RandomColor: TColor;
begin
Result := RGB(Random(256), Random(256), Random(256))
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to RichEdit1.Lines.Count - 1 do
begin
RichEdit1.CaretPos := Point(0, i);
RichEdit1.SelLength := RichEdit1.Lines[i].Length;
RichEdit1.SelAttributes.Color := RandomColor;
end;
end;
如果 richedit 控件的内容没有被分成几行,而是根据控件的大小动态换行(可能会随着表单调整大小而改变),那么您可以使用此过程为行之间交替着色红色、绿色、蓝色:
procedure TForm1.Button1Click(Sender: TObject);
const
ColorWheel: array[0..2] of TColor = (clRed, clGreen, clBlue);
var
RowNr, RowStartPos, RowEndPos, C: Integer;
HasReachedEnd: Boolean;
begin
HasReachedEnd := False;
RowStartPos := 0;
C := 0;
RowNr := 1;
repeat
RowEndPos := RichEdit1.Perform(EM_LINEINDEX, RowNr, 0);
if RowEndPos = -1 then
begin
// Last row reached
HasReachedEnd := True;
RowEndPos := RichEdit1.GetTextLen;
end;
// Select text
RichEdit1.SelStart := RowStartPos;
RichEdit1.SelLength := RowEndPos - RowStartPos;
// Change selected text colour
RichEdit1.SelAttributes.Color := ColorWheel[C];
C := (C + 1) mod 3;
// Prepare for next row
RowStartPos := RowEndPos;
Inc(RowNr);
until HasReachedEnd;
end;
如何逐行更改 Rich Edit 的文本颜色?这取决于位置。第一行必须是红色,第二行必须是绿色等等。问题是 Rich Edit 的文本已经载入。因此必须在文本已经在控件中后更改它。我正在使用 Delphi.
最好从一开始就加载正确的颜色。
但要回答你的问题,一个快速、肮脏且相当丑陋的解决方案是
function RandomColor: TColor;
begin
Result := RGB(Random(256), Random(256), Random(256))
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to RichEdit1.Lines.Count - 1 do
begin
RichEdit1.CaretPos := Point(0, i);
RichEdit1.SelLength := RichEdit1.Lines[i].Length;
RichEdit1.SelAttributes.Color := RandomColor;
end;
end;
如果 richedit 控件的内容没有被分成几行,而是根据控件的大小动态换行(可能会随着表单调整大小而改变),那么您可以使用此过程为行之间交替着色红色、绿色、蓝色:
procedure TForm1.Button1Click(Sender: TObject);
const
ColorWheel: array[0..2] of TColor = (clRed, clGreen, clBlue);
var
RowNr, RowStartPos, RowEndPos, C: Integer;
HasReachedEnd: Boolean;
begin
HasReachedEnd := False;
RowStartPos := 0;
C := 0;
RowNr := 1;
repeat
RowEndPos := RichEdit1.Perform(EM_LINEINDEX, RowNr, 0);
if RowEndPos = -1 then
begin
// Last row reached
HasReachedEnd := True;
RowEndPos := RichEdit1.GetTextLen;
end;
// Select text
RichEdit1.SelStart := RowStartPos;
RichEdit1.SelLength := RowEndPos - RowStartPos;
// Change selected text colour
RichEdit1.SelAttributes.Color := ColorWheel[C];
C := (C + 1) mod 3;
// Prepare for next row
RowStartPos := RowEndPos;
Inc(RowNr);
until HasReachedEnd;
end;