Eszee
Eszee

Reputation: 262

How to draw items in listbox in a different color

My question is basically the same as this question. However, I want make the color flow from left to right from a set color to white. The idea is that I want to "fill" every item to 100% and that gradually changes the color from green to yellow to red.

Upvotes: 3

Views: 6635

Answers (1)

huxahetu
huxahetu

Reputation: 193

Try this code:

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.

Upvotes: 1

Related Questions