Delphi TPopupMenu design modifications - delphi

Can we achieve the below look and feel with TPopupMenu VCl component
Can someone guide us in achieving the design?
I have tried setting OwnerDraw to True and wrote the OnDrawItem for menu items, But that is not successfull.
procedure TForm.tCopyDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean);
var
s: string;
begin
// change font
ACanvas.Font.Name := 'Noto Sans';
ACanvas.Font.Size := 12;
//ACanvas.Font.Style := [fsBold];
ACanvas.Font.Color := $00757575;
// change background
ACanvas.Brush.Color := clWindow;
ACanvas.Rectangle(ARect);
// write caption/text
s := (Sender as TMenuItem).Caption;
//ACanvas.TextOut(ARect.Left + 2, ARect.Top + 2 , s);
ACanvas.TextOut(-2, -2, s);
end;
after compiling this I got the look and feel like below.
I have to eliminate that black border and align the items vertically.
UPDATE
I have managed to write some code to get the UI as shown in the image but only the Vertical line separator in-between icons and text is missing.
My code is as below:
procedure TForm1.pmiProjectCopyDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
var
bt: Tbitmap;
begin
bt := Tbitmap.Create;
with TMenuItem(Sender) do
begin
with ACanvas do
begin
Brush.Color := clWhite;
FillRect(ARect);
pen.Color := $00E5DFD7;
if Selected then
begin
Font.Color := $006C4E1F;
end
else
begin
Font.Color := $00757575;
end;
Font.Size := 8;
Font.Name := 'Noto Sans';
if Caption = '-' then
begin
MoveTo(ARect.left + 25, ARect.Top + 3);
LineTo(ARect.Width, ARect.Top + 3);
end
else
begin
ImageList1.GetBitmap(ImageIndex, bt);
Draw(ARect.left + 3, ARect.Top + 3, bt);
ARect.left := ARect.left + 25;
DrawText(ACanvas.Handle, PChar(Caption), Length(Caption), ARect,
DT_SINGLELINE or DT_VCENTER);
DrawText(ACanvas.Handle, PChar(ShortCutToText(shortcut)),
Length(ShortCutToText(shortcut)), ARect, DT_SINGLELINE or DT_RIGHT);
end;
end;
end;
end;
when i compile this code my output is as below :
Only thing left is I want to get a vertical line as shown in below image:

I have managed to write some code to get the UI as shown in the image but only the Vertical line separator in-between icons and text is missing.
My code is as below:
procedure TForm1.pmiProjectCopyDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
var
bt: Tbitmap;
begin
bt := Tbitmap.Create;
with TMenuItem(Sender) do
begin
with ACanvas do
begin
Brush.Color := clWhite;
FillRect(ARect);
pen.Color := $00E5DFD7;
if Selected then
begin
Font.Color := $006C4E1F;
end
else
begin
Font.Color := $00757575;
end;
Font.Size := 8;
Font.Name := 'Noto Sans';
if Caption = '-' then
begin
MoveTo(ARect.left + 25, ARect.Top + 3);
LineTo(ARect.Width, ARect.Top + 3);
end
else
begin
ImageList1.GetBitmap(ImageIndex, bt);
Draw(ARect.left + 3, ARect.Top + 3, bt);
ARect.left := ARect.left + 25;
DrawText(ACanvas.Handle, PChar(Caption), Length(Caption), ARect,
DT_SINGLELINE or DT_VCENTER);
DrawText(ACanvas.Handle, PChar(ShortCutToText(shortcut)),
Length(ShortCutToText(shortcut)), ARect, DT_SINGLELINE or DT_RIGHT);
end;
end;
end;
end;
when i compile this code my output is as below :
Only thing left is I want to get a vertical line as shown in below image:

I have to eliminate that black border and align the items vertically.
This is written in C++. I've assumed that the MenuItem string is known.
The DoGetMenuString function is not accessible.
void __fastcall TForm1::Undo1DrawItem(TObject *Sender, TCanvas *ACanvas,
TRect &ARect, bool Selected)
{
// The assumptions are that the Canvas colors etc and the Rect sizes
// are already set by the program
// The text has two spaces at the front and four spaces at the end
const AnsiString ItemStr(" Undo Ctrl+Z ");
// calculate the position to draw the text
static int textpos = (ARect.Height() - ACanvas->TextHeight(ItemStr)) / 2;
// choose the color for the text
if( Selected)
ACanvas->Font->Color = clCream;
else
ACanvas->Font->Color = clAqua;
// Fill the whole rectangle
ACanvas->FillRect(ARect);
// write text to Canvas
ACanvas->TextOut(
ARect.Left,
textpos,
ItemStr);
}

Related

Howto create same style of tMenuItem with AdvancedDrawItem?

I would like to add a Line with a specific color for each MenuItem of popup menu in Tokyo VCL app. The Style is "Amethyst Kamri".
I'm invoked the AdvancedDrawItem event of each MenuItem as below. However, the hilighted box is flat and has not the same 3d shape as the non-ownerdraw look.
The flat background (in Orange):
While I would like to get it:
Howto implement it better? Delphi 10.2, VCL.
procedure TForm1.mnuColorAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; State: TOwnerDrawState);
var
MenuItem : tMenuItem;
LStyles : TCustomStyleServices;
LDetails : TThemedElementDetails;
begin
MenuItem := (Sender as TMenuItem);
LStyles := StyleServices;
ACanvas.Brush.Style := bsClear;
ACanvas.Font.Color := LStyles.GetStyleFontColor(sfPopupMenuItemTextNormal);
//check the state
if odSelected in State then
begin
ACanvas.Brush.Color := LStyles.GetSystemColor(clHighlight);
ACanvas.Font.Color := LStyles.GetSystemColor(clHighlightText);
end;
ACanvas.FillRect(ARect);
ARect.Left := ARect.Left + 2;
//draw the text
ACanvas.TextOut(ARect.Left + 2, ARect.Top, MenuItem.Caption);
end;
Thanks
Reron
I more or less find a solution. The problem was using Canvas FillRect.
Assume three PopUp menu items, Red, Green and Blue. The line color for each of them is stored in each Tag field. Each Menu-line is composed from three elements: A Check mark, a Color line and the Caption.
All three items have a common event ColorAdvancedDrawItem.
All Owner draw methods are based on Styles and not on direct Canvas drawing, except the new lines. See code:
procedure TForm1.ColorAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; State: TOwnerDrawState);
const
CheckBoxWidth = 20;
LineLen = 25;
var
MenuItem : tMenuItem;
LStyles : TCustomStyleServices;
LDetails : TThemedElementDetails;
CheckBoxRect, LineRect, TextRect: TRect;
Y: integer;
begin
MenuItem := (Sender as TMenuItem);
LStyles := StyleServices;
// Draw Check box
if MenuItem.Checked then
begin
LDetails := StyleServices.GetElementDetails(tmPopupCheckNormal);
CheckBoxRect := ARect;
CheckBoxRect.Width := CheckBoxWidth;
LStyles.DrawElement(ACanvas.Handle, LDetails, CheckBoxRect);
end;
// Draw text
// Check the state
if odSelected in State then
LDetails := StyleServices.GetElementDetails(tmPopupItemHot)
else
LDetails := StyleServices.GetElementDetails(tmPopupItemNormal);
TextRect := ARect;
TextRect.Left := CheckBoxWidth + LineLen;
LStyles.DrawText(ACanvas.Handle, LDetails, MenuItem.Caption, TextRect, [tfLeft, tfSingleLine, tfVerticalCenter]);
// Draw Line
ACanvas.Pen.Color := tColor(MenuItem.Tag);
ACanvas.Pen.Width := 2;
LineRect := ARect;
LineRect.Left := CheckBoxWidth;
LineRect.Width:= LineLen;
Y := LineRect.Top + (LineRect.Height div 2);
ACanvas.MoveTo(LineRect.Left+2, Y);
ACanvas.LineTo(LineRect.Left + LineRect.Width - 2, Y);
end;
The results looks like:

Creating a transparent custom bitmap brush

Problem Definition
I am trying to create a custom bitmap brush with transparency but it doesn't seem to be working as expected. If you look at this example. Add the code and hook up the paint, create and destroy events.
type
TForm3 = class(TForm)
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
FBitmap: TBitmap;
end;
// Implementation
function CreateBlockBitmap(const APenColor: TColor): TBitmap;
begin
Result := TBitmap.Create;
Result.Transparent := True;
Result.Canvas.Brush.Color := clWhite;
Result.Canvas.Brush.Style := bsClear;
Result.PixelFormat := pf32bit;
Result.SetSize(20, 20);
Result.Canvas.Brush.Color := APenColor;
Result.Canvas.Brush.Style := bsSolid;
Result.Canvas.FillRect(Rect(0,0,10,10));
end;
procedure TForm3.FormDestroy(Sender: TObject);
begin
FBitmap.Free;
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
FBitmap := CreateBlockBitmap(clRed);
end;
procedure TForm3.FormPaint(Sender: TObject);
var
colNum: Integer;
rowNum: Integer;
begin
// Paint the rectangle using the brush
Canvas.Pen.Color := clGreen;
Canvas.Brush.Bitmap := FBitmap; // This is using bitmap
Canvas.Rectangle(50, 50, 250, 250);
// Draw the block using Canvas.Draw
for rowNum := 0 to 9 do
for colNum := 0 to 9 do
Canvas.Draw(350 + rowNum * 20, 50 + colNum * 20, FBitmap);
end;
This code produces two painted blocks. The left one is painted using a bitmap brush and the right hand side one is painted using a number of Canvas.Draw calls.
I need the brush to be painted with transparency similar to what would happen if you used a hatch brush. This SO answer seems to indicate that it's possible:
How can I draw a patternBrush with transparent backround (GDI)?
What I have tried
1) I tried using a solid background color instead of using bsClear. This just makes the background white.
Result.Canvas.Brush.Color := clWhite;
Result.Canvas.Brush.Style := bsSolid;
If I use clFuchsia then the color is Fuchsia. I also tried painting the background clFuchsia and then setting the TransparentColor to clFuchsia. The Canvas.Draw option paints with transparency and the brush doesn't.
2) I tried setting the alpha channel directly with the following code:
procedure SetAlphaBitmap(const Dest: TBitmap;Color : TColor;Alpha:Byte);
type
TRGB32 = record
B, G, R, A: byte;
end;
PRGBArray32 = ^TRGBArray32;
TRGBArray32 = array[0..0] of TRGB32;
var
x, y: integer;
Line, Delta: integer;
ColorRGB : TColor;
begin
if Dest.PixelFormat<>pf32bit then exit;
ColorRGB := ColorToRGB(Color);
Line := integer(Dest.ScanLine[0]);
Delta := integer(Dest.ScanLine[1]) - Line;
for y := 0 to Dest.Height - 1 do
begin
for x := 0 to Dest.Width - 1 do
if TColor(RGB(PRGBArray32(Line)[x].R, PRGBArray32(Line)[x].G, PRGBArray32(Line)[x].B)) = ColorRGB then
PRGBArray32(Line)[x].A := Alpha;
Inc(Line, Delta);
end;
end;
And then calling this routine immediately after the rectangle has been painted using the background color.
Result.Canvas.Brush.Style := bsSolid;
Result.Canvas.FillRect(Rect(0,0,10,10));
SetAlphaBitmap(Result, clBlack, 0); // Set the alpha channel
end;
I know that the alpha channel is working because if I pass in an alpha value of 255 then it shows up in black in the Canvas.Draw too.
SetAlphaBitmap(Result, clBlack, 255);
3) I tried testing by creating a pattern brush and assigning that instead of the bitmap. That produces exactly the same results. FBrush is an HBRUSH.
FBrush := CreatePatternBrush(FBitmap.Handle);
And the setting the brush like this:
Canvas.Brush.Handle := FBrush;
4) I tried calling SetBkMode as indicated in the SO answer above. That made no difference at all.
Canvas.Pen.Color := clGreen;
Canvas.Brush.Bitmap := FBitmap;
SetBkMode(Canvas.Handle, TRANSPARENT); // This doesn't make a difference
Canvas.Rectangle(50, 50, 250, 250);
Edit
5) I just tested with a Monochrome bitmap and it has the same problem. The image is painted with a white background and black foreground for the brush and transparent for the Canvas.Draw.
function CreateMonochromeBitmap: TBitmap;
begin
Result := TBitmap.Create;
Result.Transparent := True;
Result.Canvas.Brush.Color := clWhite;
Result.Canvas.Brush.Style := bsSolid;
Result.PixelFormat := pf1bit;
Result.SetSize(20, 20);
Result.Canvas.Brush.Color := clBlack;
Result.Canvas.Brush.Style := bsSolid;
Result.Canvas.FillRect(Rect(0,0,10,10));
end;
And in the constructor:
FBitmap := CreateMonochromeBitmap;
FBrush := CreatePatternBrush(FBitmap.Handle);
In the paint we set the handle rather than the bitmap property.
Canvas.Brush.Handle := FBrush;
Try to clear the canvas this null color before your drawing loop.
Canvas.Clear(TAlphaColorRec.Null);
Greetings.
Pau.
You need to use white color for transparent areas and SetROP2 before filling the rectangle, like this:
Canvas.Brush.Bitmap := FBitmap; // This is using bitmap
SetROP2(Canvas.Handle, R2_MASKPEN);
Canvas.Rectangle(50, 50, 250, 250);
And don't forget to restore the previous ROP mode.
Good luck!
Solved! Here is my solution:
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
public
FBitmap: TBitmap;
end;
//Implementation
function CreateBlockBitmap: TBitmap;
begin
Result := TBitmap.Create;
Result.PixelFormat := pf1bit; //!! 1-bit
Result.Width := 20;
Result.Height := 20;
Result.Canvas.Brush.Color := clBlack;
Result.Canvas.FillRect(Rect(0, 0, 10, 10));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FBitmap := CreateBlockBitmap;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FBitmap.Free;
end;
procedure TForm1.FormPaint(Sender: TObject);
const
PatternColor = clRed; //brush color to be used
var
R: TRect;
begin
//filling the background with different colors for test
Canvas.Brush.Color := clGreen;
Canvas.FillRect(Rect(0,0,100,600));
Canvas.Brush.Color := clAqua;
Canvas.FillRect(Rect(100,0,200,600));
Canvas.Brush.Color := clYellow;
Canvas.FillRect(Rect(200,0,300,600));
Canvas.Brush.Color := clWhite;
Canvas.FillRect(Rect(300,0,400,600));
//draw the rectangle
R := Rect(50, 50, 500, 500);
Canvas.Brush.Color := PatternColor;
BitBlt(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom, Canvas.Handle, 0, 0, PATINVERT);
Canvas.Brush.Bitmap := FBitmap;
SetROP2(Canvas.Handle, R2_MASKPEN);
Canvas.Rectangle(R); //draw any figure here
Canvas.Brush.Color := PatternColor;
SetROP2(Canvas.Handle, R2_COPYPEN);
BitBlt(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom, Canvas.Handle, 0, 0, PATINVERT);
end;

How to draw transparent text on form?

Is there a way to draw a transparent text on form that has some controls? If I use TLabel control, it would always show behind controls on the form.
You cannot use a TLabel control, since it is not a windowed control, and therefore it will be hidden by every windowed child control of the form. You could use a TStaticText, which is indeed a windowed control (a STATIC control), but it will be a bit difficult to make it truly transparent, I'd suppose.
You can use layered windows for this:
Create a new VCL project, and add a bunch of windowed controls to it.
Create a new form in the project, named splash. Set BorderStyle to bsNone, and set the font name, size, and colour to whatever you desire (e.g., Segoe UI, 42, red).
Add a public method
procedure Tsplash.UpdateSplash(const Str: string);
var
R: TRect;
P: TPoint;
S: TPoint;
bm: TBitmap;
bf: TBlendFunction;
EXSTYLE: DWORD;
x, y: integer;
pixel: PRGBQuad;
TextRed,
TextGreen,
TextBlue: byte;
begin
EXSTYLE := GetWindowLong(Handle, GWL_EXSTYLE);
SetWindowLong(Handle, GWL_EXSTYLE, EXSTYLE or WS_EX_LAYERED);
R := ClientRect;
bm := TBitmap.Create;
try
bm.PixelFormat := pf32bit;
bm.SetSize(ClientWidth, ClientHeight);
bm.Canvas.Brush.Color := clBlack;
bm.Canvas.FillRect(ClientRect);
bm.Canvas.Font.Assign(Self.Font);
bm.Canvas.Font.Color := clWhite;
DrawText(bm.Canvas.Handle, PChar(Str), Length(Str), R,
DT_SINGLELINE or DT_VCENTER or DT_CENTER or DT_WORD_ELLIPSIS);
TextRed := GetRValue(Font.Color);
TextGreen := GetGValue(Font.Color);
TextBlue := GetBValue(Font.Color);
for y := 0 to bm.Height - 1 do
begin
pixel := bm.ScanLine[y];
x := 0;
while x < bm.Width do
begin
with pixel^ do
begin
rgbReserved := (rgbRed + rgbGreen + rgbBlue) div 3;
rgbBlue := TextBlue * rgbReserved div 255;
rgbGreen := TextGreen * rgbReserved div 255;
rgbRed := TextRed * rgbReserved div 255;
end;
inc(pixel);
inc(x);
end;
end;
P := Point(0, 0);
S := Point(bm.Width, bm.Height);
bf.BlendOp := AC_SRC_OVER;
bf.BlendFlags := 0;
bf.SourceConstantAlpha := 255;
bf.AlphaFormat := AC_SRC_ALPHA;
UpdateLayeredWindow(Handle, 0, nil, #S, bm.Canvas.Handle, #P, 0, #bf,
ULW_ALPHA)
finally
bm.Free;
end;
end;
To your main form, add private methods
procedure TForm1.CreateSplash;
var
p: TPoint;
begin
splash.Visible := true;
UpdateSplash;
end;
procedure TForm1.UpdateSplash;
var
p: TPoint;
begin
if not (Assigned(splash) and splash.Visible) then Exit;
p := ClientToScreen(Point(0, 0));
splash.SetBounds(p.X, p.Y, ClientWidth, ClientHeight);
splash.UpdateSplash('Sample Text');
end;
and call UpdateSplash every time the form is moved or resized:
procedure TForm1.WMMove(var Message: TWMMove);
begin
UpdateSplash;
end;
procedure TForm4.FormResize(Sender: TObject);
begin
UpdateSplash;
end;
Finally, you can do, just to try it out,
procedure TForm1.FormClick(Sender: TObject);
begin
if splash.Visible then
splash.Hide
else
CreateSplash;
end;
Compiled demo EXE

Drawing a Progress Bar using TStringGrid's OnDrawCell event [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Grid progressbar or animation
Add graphical bar to a StringGrid col
Using Delphi 2010, I have a TStringGrid with 5 columns
ID, Start, End, Duration, and a column to draw a progress bar in each cell.
column 5 width (example: 60) is set by the Bar width spin edit field in options dialog.
Given that duration is (end - start) * 1440 (example: 0.39 minutes), I need to draw the progress bar as a percentage of the total bar width. (i.e. 39/60 = 65%) therefore the bar should be painted 65% accross the cell. It also needs to show the percentage centered in the bar. (navy blue bar & white text).
can anyone help me to paint this progress bar ?
procedure Tphasedata.grdMainDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
LStrCell: string;
LRect: TRect;
begin
with (Sender as TStringGrid) do
begin
// Don't change color for first Column, first row
if (ACol = 0) or (ARow = 0) then
Canvas.Brush.Color := clBtnFace
else
begin
case ACol of
0: Canvas.Font.Color := clBlack;
1: Canvas.Font.Color := clBlue;
2: Canvas.Font.Color := clBlue;
3: Canvas.Font.Color := clRed;
end;
// Draw the Band
if ARow mod 2 = 0 then
Canvas.Brush.Color := $00E1FFF9
else
Canvas.Brush.Color := $00FFEBDF;
Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, cells[acol, arow]);
Canvas.FrameRect(Rect);
//center the duration text
if ACol = 3 then
begin
LStrCell := Cells[ACol, ARow]; // grab cell text
Canvas.FillRect(Rect); // clear the cell
LRect := Rect;
LRect.Top := LRect.Top + 3; // adjust top to center vertical
// draw text
DrawText(Canvas.Handle, PChar(LStrCell), Length(LStrCell), LRect, DT_CENTER);
end;
i ACol = 4 then
begin
// draw progress bar here
end;
end;
end;
var
percent:Double;
procedure DrawTheText(const hDC: HDC; const Font: TFont; var Text: string; aRect:TRect);
var
lRect:Trect;
begin
with TBitmap.Create do
try
Width := aRect.Right - aRect.Left;
Height := aRect.Bottom - aRect.Top;
LRect :=Rect(0,0,width,height);
Canvas.Font.Assign(Font);
Canvas.Brush.Color := clBlack;
Canvas.FillRect(Lrect);
Canvas.Font.Color := clWhite;
Canvas.TextRect(Lrect,Text,[tfCenter ,tfVerticalCenter,tfSingleLine]);
BitBlt(hDC, aRect.Left, aRect.Top, Width, Height, Canvas.Handle, 0, 0, SRCINVERT);
finally
Free;
end;
end;
procedure TForm3.DrawGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
LRect:Trect;
s:String;
c:TCanvas;
begin
//.....yout code
percent := 0.5;//Random(2) / 60;
//.... case of wished Colum
c := DrawGrid1.Canvas;
LRect := Rect;
LRect.Right := Round(LRect.Left + (LRect.Right - LRect.Left)*percent);
inflaterect(LRect,-1,-1);
c.Brush.Color := clNavy;
c.Brush.Style := bsSolid;
c.Pen.Color := clBlack;
C.FillRect(LRect);
s := FormatFloat('0.00 %' , percent * 100 );
DrawTheText(c.Handle,DrawGrid1.font,s,rect);
end;

Add graphical bar to a StringGrid col

Using Delphi 2010 and a TStringGrid component, I currently display five filds from a database query.
Here is a simplied example of what i am doing
//set up the grid
procedure TGriddata.FormCreate(Sender: TObject);
begin
grdMain.Rows[0].commatext:='"One","Two","Three","Four","Five"';
grdMain.ColWidths[0]:= 50;
grdMain.ColWidths[1]:= 175;
grdMain.ColWidths[2]:= 175;
grdMain.ColWidths[3]:= 100;
grdMain.ColWidths[4]:= 300;
end;
//display the data in the grid
//note, I am not showing my creation, execution, or destroy of the query
procedure TGriddata.load;
begin
...
grdMain.Cells[0,row]:= FieldByName('one').AsString;
grdMain.Cells[1,row]:= FieldByName('two').AsString;
grdMain.Cells[2,row]:= FieldByName('three').AsString;
grdMain.Cells[3,row]:= FieldByName('four').AsString;
//draw progress bar here
...
end;
One of the columns ("Five") needs to display a navy blue horizontal bar in the col. It should also diplay some text centered in the bar. I have no expereince using the custom drawing. What properties do i set to only custom draw the one column and use the default drawing for the other columns?
Add the text to the cells like you normally would. But you have to draw those bars in the OnDrawCell event. Leave DefaultDrawing as is (True by default), and erase the already drawn cell text in those columns by filling it in advance:
procedure TForm1.grdMainDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
Progress: Single;
R: TRect;
Txt: String;
begin
with TStringGrid(Sender) do
if (ACol = 4) and (ARow >= FixedRows) then
begin
Progress := StrToFloatDef(Cells[ACol, ARow], 0) / 100;
Canvas.FillRect(Rect);
R := Rect;
R.Right := R.Left + Trunc((R.Right - R.Left) * Progress);
Canvas.Brush.Color := clNavy;
Canvas.Rectangle(R);
Txt := Cells[ACol, ARow] + '%';
Canvas.Brush.Style := bsClear;
IntersectClipRect(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom);
Canvas.Font.Color := clHighlightText;
DrawText(Canvas.Handle, PChar(Txt), -1, Rect, DT_SINGLELINE or
DT_CENTER or DT_VCENTER or DT_END_ELLIPSIS or DT_NOPREFIX);
SelectClipRgn(Canvas.Handle, 0);
ExcludeClipRect(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom);
Canvas.Font.Color := clWindowText;
DrawText(Canvas.Handle, PChar(Txt), -1, Rect, DT_SINGLELINE or
DT_CENTER or DT_VCENTER or DT_END_ELLIPSIS or DT_NOPREFIX);
SelectClipRgn(Canvas.Handle, 0);
end;
end;
For more options, you might consider this DrawStatus routine.
Here you can view a sample (Draw percentage in a cell in a Grid), to draw a bar in a cell of a TStringGrid.
The explanation is in spanish, but you can download the code, that is very simple.
Also you can use authomatic translation on right of page.
procedure TFormDrawCell.DBGrid1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
const
STR_EMPTY = '';
CHAR_PERCENT = '%';
SPACE_TO_CENTER_CELLTEXT = 0;
var
fValue: Integer;
ActualPenColor, ActualBrushColor: TColor;
EmptyDS: Boolean;
DrawRect: TRect;
fWidth1, fLeft2: Integer;
StrValue: string;
begin
if not (Column.FieldName = 'Precent') then
Exit;
if not (cbdraw.Checked) then
Exit;
EmptyDS := ((TDBGrid(Sender).DataSource.DataSet.EoF) and
(TDBGrid(Sender).DataSource.DataSet.Bof));
if (Column.Field.IsNull) then begin
fValue := -1;
StrValue := STR_EMPTY;
end
else begin
fValue := Column.Field.AsInteger;
StrValue := IntToStr(fValue) + CHAR_PERCENT;
end;
DrawRect := Rect;
InflateRect(DrawRect, -1, -1);
fWidth1 := (((DrawRect.Right - DrawRect.Left) * fValue) DIV 100);
ActualPenColor := TDBGrid(Sender).Canvas.Pen.Color;
ActualBrushColor := TDBGrid(Sender).Canvas.Brush.Color;
TDBGrid(Sender).Canvas.Pen.Color := clHighlight;
TDBGrid(Sender).Canvas.Brush.Color := clWhite;
TDBGrid(Sender).Canvas.Rectangle(DrawRect);
if (fValue > 0) then begin
TDBGrid(Sender).Canvas.Pen.Color := clSkyBlue;
TDBGrid(Sender).Canvas.Brush.Color := clSkyBlue;
DrawRect.Right := DrawRect.Left + fWidth1;
InflateRect(DrawRect, -1, -1);
TDBGrid(Sender).Canvas.Rectangle(DrawRect);
end;
if not (EmptyDS) then begin
DrawRect := Rect;
InflateRect(DrawRect, -2, -2);
TDBGrid(Sender).Canvas.Brush.Style := bsClear;
fLeft2 := DrawRect.Left + (DrawRect.Right - DrawRect.Left) shr 1 -
(TDBGrid(Sender).Canvas.TextWidth(StrValue) shr 1);
TDBGrid(Sender).Canvas.TextRect(DrawRect, fLeft2,
DrawRect.Top + SPACE_TO_CENTER_CELLTEXT, StrValue);
end;
TDBGrid(Sender).Canvas.Pen.Color := ActualPenColor;
TDBGrid(Sender).Canvas.Brush.Color := ActualBrushColor;
end;
Regards.

Resources