Delphi – Easiest way to make a button with just a image

delphidelphi-xevcl

I'm using Delphi XE and I would like to make a button which shows just the provided PNG image with transparent background and no additional margins of any kind.

I tried to do this with TButton but I get an ugly gray background with bsPushButton style. If I use bsCommandLink style there is a 10 pixel top margin although all my ImageMargins settings are set to 0.

What would be the easiest way to make this happen?

EDIT: It doesn't have to look like a button. I just need it to look exactly like the image it is assigned with. Preferably it should be able to be a tab stop and have various states (enabled, disabled, hover, …) so I could assign appropriate image to each state.

Best Answer

What you want is a transparent control that inherits from TWinControl since you want it to be able to retrieve focus, this has never been an easy task. However since recent versions Embarcadero has provided a control that provides this. The TCustomTransparentControl is a TWinControl descendent that makes the task a bit easier for you.

So, what I would do is to create a new component, and inherit it from TCustomTransparentControl, then what I would do is to overwrite the Paint method like this:

procedure TMyTransparentButton.Paint;
var
  rc: TRect;
begin
  if not (csDestroying in ComponentState) then
  begin
    // Specify size and location of the image.
    rc := Rect(0, 0, pngImage.Width, pngImage.Height);

    // Draw the image on the canvas.
    pngImage.Draw(Canvas, rc);
  end;
end;

By this approach you should be able to get the transparency and translucency you are looking for. However you still need to handle the situation where the button is disabled, pressed, etc.

Related Topic