Delphi 迷幻色彩问题
如果Delphi 迷幻色彩问题,delphi,trichedit,Delphi,Trichedit,如果ans中的字母与correct字符串中的字母在同一位置匹配,则该字母为红色,否则为蓝色 我的问题是,当我再次键入时,整个RichEdit1文本的颜色与第一个字母相同(如果RichEdit1的第一个字母为蓝色,则整个文本变为蓝色) 顺便说一句,这不是实际的代码,我只是简化了它,因为它有多个技巧。 这些技巧是只读的,我通过RichEdit1.Text:=RichEdit1.Text+Key (这样做是因为它是一个多键盘程序,我需要分离用户输入) 这是正确的行为吗?如何阻止颜色更改覆盖默认颜色?
ans
中的字母与correct
字符串中的字母在同一位置匹配,则该字母为红色,否则为蓝色
我的问题是,当我再次键入时,整个RichEdit1文本的颜色与第一个字母相同(如果RichEdit1
的第一个字母为蓝色,则整个文本变为蓝色)
顺便说一句,这不是实际的代码,我只是简化了它,因为它有多个技巧。这些技巧是只读的,我通过
RichEdit1.Text:=RichEdit1.Text+Key代码>
(这样做是因为它是一个多键盘程序,我需要分离用户输入)
这是正确的行为吗?如何阻止颜色更改覆盖默认颜色?
更新:解决了它。。。以一种草率的方式(每当有人键入时应用默认颜色),但我会保持这个打开状态,以防有人提出更好的解决方案。
正如您已经发现的,完成后必须重置默认颜色,例如:
ans:= RichEdit1.Text
for i:=1 to Length(ans) do
begin
RichEdit1.SelStart := i-1;
RichEdit1.SelLength:= 1;
if ans[i] = correct[i] then
RichEdit1.SelAttributes.Color := clRed
else
RichEdit1.SelAttributes.Color := clBlue;
有比一次给一个字母上色更有效的方法来处理这个问题,例如:
ans := RichEdit1.Text;
for i := 1 to Length(ans) do
begin
RichEdit1.SelStart := i-1;
RichEdit1.SelLength := 1;
if ans[i] = correct[i] then
RichEdit1.SelAttributes.Color := clRed
else
RichEdit1.SelAttributes.Color := clBlue;
end;
RichEdit1.SelStart := RichEdit1.GetTextLen;
RichEdit1.SelLength := 0;
RichEdit1.SelAttributes.Color := RichEdit1.Font.Color;
此外,使用Text属性附加单个字符的效率非常低。请改用SelText属性,例如:
const
colors: array[Boolean] of TColor = (clRed, clBlue);
var
ans: string;
start, len: Integer;
cur_state: Boolean;
procedure ColorRange(AStart, ALength: Integer; AColor: TColor);
begin
RichEdit1.SelStart := AStart;
RichEdit1.SelLength := ALength;
RichEdit1.SelAttributes.Color := AColor;
end;
begin
RichEdit1.Lines.BeginUpdate;
try
ans := RichEdit1.Text;
start := 0;
len := 0;
cur_start := False;
for i := 1 to Length(ans) do
begin
if (ans[i] = correct[i]) = cur_state then
Inc(len)
else begin
if len > 0 then
ColorRange(start, len, colors[cur_state]);
start := i-1;
len := 1;
cur_state := not cur_state;
end;
end;
if len > 0 then
ColorRange(start, len, colors[cur_state]);
ColorRange(RichEdit1.GetTextLen, 0, RichEdit1.Font.Color);
finally
RichEdit1.Lines.EndUpdate;
end;
end;
首先,您的代码甚至没有编译。。。第二,你什么时候调用这个子程序?我根据您的代码做了一个小示例,添加了更正和改进,对我来说效果非常好;(您在richedit1和selattributes.color之间添加了一个额外的.color)@JachGrate:这不是全部代码,顺便说一句,只是一个小片段。我称之为onkeypress。@omair:哦,只是一个打字错误。谢谢你指出这一点。我现在就去修,我要在OnChange事件上打电话。并非每个按键都会更改编辑内容。如前所述,它可以工作,闪烁,但我相信它可以优化,以减少更改。我知道没有办法阻止控件在每次属性更改时重新绘制,考虑像BeginUpdate/EndUpdate对这样的东西。你真了不起。谢谢D
RichEdit1.SelStart := RichEdit1.GetTextLen;
RichEdit1.SelLength := 0;
RichEdit1.SelAttributes.Color := ...; // optional
RichEdit1.SelText := Key;