TIPS: Draw Image From TImageList

This question is coming back and again.

I have a TImage in many form which shows the status of the item. It requires status image being changed when it is changed. I do not want to use several instances of the TImage on the form. Instead I would like to use TImageList to store and share them.

Yes, you can. But there are some quirks you have to consider when doing so.

Let’s say you have state images and you have to draw a different one based on the state.

Let’s say you have placed Image list and an Image on your form and populated the list with few state images

var
  MyImageList: TImageList;
  MyImage: TImage;

Canvas

That is probably the easiest case. Lets draw an image on canvas of some control (OwnerDraw situation) and also center it. X, Y are top left corner of the future image and Width is a width of the rectangle we want to center image in.
MyImageIndex is an index of the image in the Image List.

MyImageList.Draw(Canvas, X + Width div 2 - MyImageList.Width div 2, Y, MyImageIndex, dsNormal, itImage);

TImage

Being a little bit more complex, it does require some extra code.

// Make sure that any prior state is cleared.
// If you do not do that with transparency enabled, you would see
// images on top of each other
MyImage.Picture.Bitmap := nil;
// Make sure that transparency pixel in the image is taken
// in consideration
MyImage.Picture.Bitmap.TransparentMode := tmFixed;
MyImage.Picture.Bitmap.TransparentColor := clWhite;
// Load image from the Image list into TImage
MyImageList.GetBitmap(MyImageIndex, MyImage.Picture.Bitmap);

Can I use resource file?

Would you like to keep images in the file?

// Store it once
WriteComponentResFile('MyImageList.dat', MyImageList);
// Use it later
ReadComponentResFile('MyImageList.dat', MyImageList);

Not that difficult after all.

This entry was posted in Delphi and tagged , , , . Bookmark the permalink.

Leave a Reply

  • About

    From being a junior developer all the way to Development Manager position, I was always interested in new technologies. Passionate speaker, IT junky, developer, architect, team lead, and development manager - many hats, one goal - making software better and closer to people’s needs. For the most part I am using my blog as a scratch pad, writing small articles on things which I came across, was asked about more then once, and which would otherwise require additional research again and again.

    View Serguei Dosyukov's profile on LinkedIn
  • Testimonials

    I've been using this [theme] since the start. It is by far the most attractive, feature packed and stable of...

    Rhyull

    I’m a huge fan of this theme. I’ve got more than 90,000 pictures in my gallery3 running on a Ubuntu...

    Jklobo

    The greydragon theme is fantastic. It’s clean, stable and feature rich. It took me a while to decide to move...

    Ed

    more...

  • Categories