-->

Easiest way to make a button with just a image

2020-07-19 15:16发布

问题:

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.

回答1:

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.



回答2:

You could use TImage and assign the OnClick event to mimic a button. It depends if you need to receive focus or not.



回答3:

You could use TPanel and assign the OnClick event to mimic a button. Set the borders of the panel to 'flat' to make it look like there is no panel.

It is similar to the solution proposed by stukelly but it is easier to implement the enabled and hover features. For example, on hover, you can make the panel look 3D.