代码之家  ›  专栏  ›  技术社区  ›  user1580348

如何从TMenuItem上的ImageList绘制透明位图?

  •  0
  • user1580348  · 技术社区  · 6 年前

    var
      NewItem: TMenuItem;
      ThisBmp: TBitmap;
    begin
      NewItem := TMenuItem.Create(pmSendToCustomTool);
      NewItem.Caption := ThisCaption;
      NewItem.Bitmap.SetSize(16,16);
      NewItem.Bitmap.PixelFormat := pf32bit;
      NewItem.Bitmap.Transparent := True;
      NewItem.Bitmap.TransparentColor := clFuchsia;
      ThisBmp := TBitmap.Create;
      try
        ThisBmp.SetSize(16,16);
        ThisBmp.PixelFormat := pf32bit;
        ThisBmp.Transparent := True;
        ThisBmp.Canvas.Brush.Color := clFuchsia;
        ThisBmp.TransparentColor := clFuchsia; 
        MySystemImageList1.GetBitmap(AIndex, ThisBmp);
        CodeSite.Send('ThisBmp', ThisBmp);
        NewItem.Bitmap.Assign(ThisBmp);
        CodeSite.Send('NewItem.Bitmap', NewItem.Bitmap);
      finally
        ThisBmp.Free;
      end;
    

    这个BMP GetBitmap : enter image description here

    结果菜单项的外观如下: enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Remy Lebeau    6 年前

    GetBitmap() . 您必须手动绘制位图,例如:

    uses
      ..., Winapi.CommCtrl;
    
    procedure GetTransparentBitmapFromImageList(ImageList: TCustomImageList; Index: Integer; Bitmap: TBitmap);
    var
      i: integer;
    begin
      // make sure your ImageList is set to ColorDepth=cd32bit and DrawingStyle=dsTransparant beforehand...
      Bitmap.SetSize(ImageList.Width, ImageList.Height);
      Bitmap.PixelFormat := pf32bit;
      if (ImageList.ColorDepth = cd32Bit) then
      begin
        Bitmap.Transparent := False;
        Bitmap.AlphaFormat := afDefined;
      end
      else
        Bitmap.Transparent := True;
      for i := 0 to Bitmap.Height-1 do
        FillChar(Bitmap.ScanLine[i]^, Bitmap.Width*SizeOf(DWORD), $00);
      ImageList_Draw(ImageList.Handle, Index, Bitmap.Canvas.Handle, 0, 0, ILD_TRANSPARENT);
    end;
    

    或者:

    procedure GetTransparentBitmapFromImageList(ImageList: TCustomImageList; Index: Integer; Bitmap: TBitmap);
    begin
      Bitmap.PixelFormat := pf32bit;
      Bitmap.Canvas.Brush.Color := clFuschia;
      Bitmap.SetSize(ImageList.Width, ImageList.Height);
      ImageList.Draw(Bitmap.Canvas, 0, 0, AIndex, dsTransparent, itImage);
      Bitmap.Transparent := True;
      Bitmap.TransParentColor := clFuchsia;
      Bitmap.TransparentMode := tmAuto;
    end;
    

    var
      NewItem: TMenuItem;
    begin
      NewItem := TMenuItem.Create(pmSendToCustomTool);
      NewItem.Caption := ThisCaption;
      GetTransparentBitmapFromImageList(MySystemImageList1, AIndex, NewItem.Bitmap);
      CodeSite.Send('NewItem.Bitmap', NewItem.Bitmap);
    end;
    
    推荐文章