2005. május 12., csütörtök

How to load a TImageList from a resource file


Is there a way to load all the icons at once from a BMP into a TImageList? Is there a way to save all the images in a TImageList to a BMP file?


The best way to load an imagelist from a resource is to pack all images into one bitmap and load them all in one go. For this you need the bitmap, of course.

So, create a new project, drop a TImagelist on the form and add the icons to it at design-time, as usual. Add a handler for the forms OnCreate event and do this in the handler:

  bmp: TBitmap;
  i: integer;
  bmp := TBitmap.Create;
    bmp.width := imagelist1.width * imagelist1.count;
    bmp.height := imagelist1.height;
    with bmp.canvas do
      brush.color := clOlive;
      brush.style := bsSolid;
    for i := 0 to imagelist1.count - 1 do
      imagelist1.draw(bmp.canvas, i * imagelist1.width, 0, i);

The result is a "strip" bitmap with all images in the list. Open this bitmap in MSPaint and save it again under the same name as a 256 or 16 color bitmap, it will usually have a higher color depth since the VCL creates bitmaps with the color depth of your current video mode by default. The "transparent" color for this bitmap is clOlive, since that is what we filled the bitmap with before painting the images on it transparently.

The next step is to add this bitmap to a resource file and add the resource to your project. You can do that with the image editor as usual or create a RC file and add it to your project group (requires D5). The RC file would contain a line like

IMAGES1 BITMAP d:\temp\images.bmp

You can now load this resource into your projects imagelist with

imagelist2.ResInstLoad(HInstance, rtBitmap, 'IMAGES1', clOlive);

Note that the width and height setting of the imagelist has to be the same as the one you saved the images from, otherwise the bitmap will not be partitioned correctly.

Nincsenek megjegyzések:

Megjegyzés küldése