DelphiFAQ Home Search:

How do I create an icon from a bitmap?

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

You must create two bitmaps, a mask bitmap (called the "AND" bitmap) and a image bitmap (called the XOR bitmap). You can pass the handles to the "AND" and "XOR" bitmaps to the Windows API function CreateIconIndirect() and use the returned icon handle in your application.

procedure TForm1.Button1Click(Sender: TObject);
var
  IconSizeX: integer;
  IconSizeY: integer;
  AndMask  : TBitmap;
  XorMask  : TBitmap;
  IconInfo : TIconInfo;
  Icon     : TIcon;
begin
  {Get the icon size}
  IconSizeX := GetSystemMetrics(SM_CXICON);
  IconSizeY := GetSystemMetrics(SM_CYICON);

  {Create the "and" mask}
  AndMask := TBitmap.Create;
  AndMask.Monochrome := true;
  AndMask.Width := IconSizeX;
  AndMask.Height := IconSizeY;

  {Draw on the "and" mask}
  AndMask.Canvas.Brush.Color := clWhite;
  AndMask.Canvas.FillRect(rect(0, 0, IconSizeX, IconSizeY));
  AndMask.Canvas.Brush.Color := clblack;
  AndMask.Canvas.ELLIPSE(4, 4, IconSizeX-4, IconSizeY-4);

  {Draw as a test}
  Form1.Canvas.Draw(IconSizeX*2, IconSizeY, AndMask);

  {Create the "xor" mask}
  XorMask := TBitmap.Create;
  XorMask.Width := IconSizeX;
  XorMask.Height := IconSizeY;

  {Draw on the "xor" mask}
  XorMask.Canvas.Brush.Color := clblack;
  XorMask.Canvas.FillRect(rect(0, 0, IconSizeX, IconSizeY));
  XorMask.Canvas.Pen.Color := clRed;
  XorMask.Canvas.Brush.Color := clRed;
  XorMask.Canvas.ELLIPSE(4, 4, IconSizeX-4, IconSizeY-4);

  {Draw as a test}
  Form1.Canvas.Draw(IconSizeX*4, IconSizeY, XOrMask);

  {Create a icon}
  Icon := TIcon.Create;
  IconInfo.fIcon := true;
  IconInfo.xHotspot := 0;
  IconInfo.yHotspot := 0;
  IconInfo.hbmMask := AndMask.Handle;
  IconInfo.hbmColor := XOrMask.Handle;
  Icon.Handle := CreateIconIndirect(IconInfo);

  {Destroy the temporary bitmaps}
  AndMask.Free;
  XorMask.Free;

  {Draw as a test}
  Form1.Canvas.Draw(IconSizeX*6, IconSizeY, Icon);

  {Assign the application icon}
  Application.Icon := Icon;

  {Force a repaint}
  InvalidateRect(Application.Handle, nil, true);

  {Free the icon}
  Icon.Free;
end;
You don't like the formatting? Check out SourceCoder then!

Comments:

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: