21

I've run into a bit of a snag, is it just me or can you not assign an image from a resource to TSpeedButton's glyph without a hideous black outline as shown below?

I've assigned it exactly the same way for the TImage component and I'm getting the result needed.

I've been searching for quite a while but no one seems to have this bizarre and annoying problem.

Here's my source code for the form below:

procedure TForm3.Button1Click(Sender: TObject);
var r : tresourcestream; png : tpngimage;
begin
  r := tresourcestream.CreateFromID(hinstance,34,'cardimage');
  png := tpngimage.Create;  
  png.LoadFromStream(r);  
  png.AssignTo(image1.Picture.bitmap);  
  png.AssignTo(speedbutton1.glyph);  
  png.Free;  
  r.Free;  
end;

34 is the image of type 'cardimage' that relates to the image being shown in the picture if you haven't guessed already.

enter image description here

Johan
  • 74,508
  • 24
  • 191
  • 319
Felix de Souza
  • 213
  • 2
  • 5
  • The issue is clearly that the alpha channel is ignored in the left picture. – Andreas Rejbrand Mar 14 '11 at 22:52
  • 2
    Generally, you should call `X.Assign(Y)`, not `Y.AssignTo(X)`. If `TX` doesn't know how acquire attributes from a `TY`, it will defer to `TY` by calling `Y.AssignTo(X)` automatically. But if `TY` doesn't know how to assign itself to a `TX`, it won't defer to the target object. – Rob Kennedy Mar 15 '11 at 01:19

1 Answers1

33

The issue is clearly that the alpha channel is ignored in the left picture. Now, the TSpeedButton.Glyph property is a TBitmap, so it might be problematic to preserve the PNG alpha channel. For example,

var
  png: TPNGImage;
begin
  png := TPngImage.Create;
  png.LoadFromFile('C:\Users\Andreas Rejbrand\Pictures\alpha.png');
  SpeedButton1.Glyph.Assign(png); // or png.AssignTo(SpeedButton1.Glyph);

produces

One partial solution is to pre-blend the PNG image:

var
  png: TPNGImage;
  bm: TBitmap;
begin
  png := TPngImage.Create;
  png.LoadFromFile('C:\Users\Andreas Rejbrand\Pictures\alpha.png');
  bm := TBitmap.Create;
  bm.SetSize(png.Width, png.Height);
  bm.Canvas.Brush.Color := Self.Color;
  bm.Canvas.FillRect(Rect(0, 0, bm.Width, bm.Height));
  bm.Canvas.Draw(0, 0, png);
  SpeedButton1.Glyph.Assign(bm);

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384