像這樣的東西應該做你想要我有什麼。假設您正在使用32bpp位圖,可能使用了alpha混合。如果要使用基於掩碼的透明度,則需要重新編寫代碼以創建適當的掩碼位圖。
procedure CopyBitmapToIcon(Bitmap: TBitmap; Icon: TIcon);
var
MonoBitmap: HBITMAP;
IconInfo: TIconInfo;
IconHandle: HICON;
begin
MonoBitmap := CreateBitmap(Bitmap.Width, Bitmap.Height, 1, 1, 0);
Try
FillChar(IconInfo, SizeOf(IconInfo), 0);
IconInfo.fIcon := True;
IconInfo.hbmMask := MonoBitmap;
IconInfo.hbmColor := Bitmap.Handle;
IconHandle := CreateIconIndirect(IconInfo);
if IconHandle=0 then begin
RaiseLastOSError;
end;
Icon.Handle := IconHandle;
Finally
DeleteObject(MonoBitmap);
End;
end;
procedure TMyForm.Button1Click(Sender: TObject);
var
Bitmap: TBitmap;
Icon: TIcon;
begin
Icon := Self.Icon;
Bitmap := TBitmap.Create;
try
Bitmap.PixelFormat := pf32bit;
Bitmap.SetSize(Icon.Width, Icon.Height);
Bitmap.Canvas.Brush.Style := bsSolid;
Bitmap.Canvas.Brush.Color := clRed;
Bitmap.Canvas.FillRect(Rect(0, 0, Icon.Width, Icon.Height));
CopyBitmapToIcon(Bitmap, Icon);
finally
Bitmap.Free;
end;
end;