Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of label caption inside ProgressBar

I want to put a label inside progress bar. And this label caption is dynamic. How can I get the label position ALWAYS on center inside the ProgressBar?

What I've tried ;

  Label1.Parent := progressBar1;
  Label1Top :=  progressBar1.Height div 2;
  Label1.Left :=  progressBar1.Width div 2

It shows ugly, and not in center like I want.

Label inside progress bar

If I set Label1.Left := progresBar1.Width div 2 - xxx it will be on center only for certain caption. I want to have any caption be placed on center.

Edited Answer from @KenWhite is working good. Solution from @DavidHeffernan just great.

ProgressBar with Text

like image 661
Bianca Avatar asked Oct 23 '14 23:10

Bianca


2 Answers

Set the label's AutoSize property to False. Change the Alignment property to taCenter and Layout to tlCenter. Size the label to the progressbar's ClientWidth and ClientHeight, and set its Left to 0.

Label1.Parent := progressBar1;
Label1.AutoSize := False;
Label1.Transparent := True;
Label1.Top :=  0;
Label1.Left :=  0;
Label1.Width := progressBar1.ClientWidth;
Label1.Height := progressBar1.ClientHeight;
Label1.Alignment := taCenter;
Label1.Layout := tlCenter;

Here's an example of the appearance:

Image of standard sized progress barImage of double height progress bar

like image 95
Ken White Avatar answered Sep 19 '22 13:09

Ken White


You might decide to derive a progress bar control that paints the text itself rather than relying on a separate label. Some sample code to demonstrate:

type
  TProgressBarWithText = class(TProgressBar)
  private
    FProgressText: string;
  protected
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
  published
    property ProgressText: string read FProgressText write FProgressText;
  end;

procedure TProgressBarWithText.WMPaint(var Message: TWMPaint);
var
  DC: HDC;
  prevfont: HGDIOBJ;
  prevbkmode: Integer;
  R: TRect;
begin
  inherited;
  if ProgressText <> '' then
  begin
    R := ClientRect;
    DC := GetWindowDC(Handle);
    prevbkmode := SetBkMode(DC, TRANSPARENT);
    prevfont := SelectObject(DC, Font.Handle);
    DrawText(DC, PChar(ProgressText), Length(ProgressText),
      R, DT_SINGLELINE or DT_CENTER or DT_VCENTER);
    SelectObject(DC, prevfont);
    SetBkMode(DC, prevbkmode);
    ReleaseDC(Handle, DC);
  end;
end;

The advantage of this approach is that your progress bar and text display are self-contained. There's no need for two separate controls that you have to coordinate.

like image 40
David Heffernan Avatar answered Sep 23 '22 13:09

David Heffernan