如何以不同的颜色在列表框中绘制项目

时间:2014-01-08 09:22:02

标签: delphi listbox

我的问题与此question基本相同。但是,我想让颜色从左到右从设定颜色流向白色。我的想法是,我希望将每个项目“填充”到100%并逐渐将颜色从绿色变为黄色再变为红色。

1 个答案:

答案 0 :(得分:0)

试试这段代码:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure ListBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure AddLog(const aStr : String; const aColor : TColor);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.AddLog(const aStr: String; const aColor: TColor);
begin
  ListBox1.Items.AddObject(aStr, TObject(aColor));
end;

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  OldColor : TColor;
begin
  with ListBox1.Canvas do begin
    OldColor := Font.Color;
    Font.Color := TColor( ListBox1.Items.Objects[Index] );
    TextOut(Rect.Left, Rect.Top, ListBox1.Items[Index]);
    Font.Color := OldColor;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Randomize;
  AddLog(
    'String #' + IntToStr(ListBox1.Items.Count),
    RGB(Random(11) * 20 , Random(11) * 20, Random(11) * 20)
  );
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  ListBox1.Clear;
end;

end.