2 // System.Windows.Forms.ImageList.cs
5 // Peter Bartok <pbartok@novell.com>
6 // Kornél Pál <http://www.kornelpal.hu/>
8 // Copyright (C) 2004-2005 Novell, Inc.
9 // Copyright (C) 2005 Kornél Pál
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 // Differences between MS.NET ImageList and this implementation:
38 // This is a fully managed image list implementation.
40 // Images are stored as Format32bppArgb internally but ColorDepth is applied
41 // to the colors of images. Images[index] returns a Format32bppArgb copy of
42 // the image so this difference is only internal.
44 // MS.NET has no alpha channel support (except for icons in 32-bit mode with
45 // comctl32.dll version 6.0) but this implementation has full alpha channel
46 // support in 32-bit mode.
48 // Handle should be an HIMAGELIST returned by ImageList_Create. This
49 // implementation uses (IntPtr)(-1) that is a non-zero but invalid handle.
51 // MS.NET creates handle when images are accessed. Add methods are caching the
52 // original images without modification. This implementation adds images in
53 // Add methods so handle is created in Add methods.
55 // MS.NET 1.x shares the same HIMAGELIST between ImageLists that were
56 // initialized from the same ImageListStreamer and doesn't update ImageSize
57 // and ColorDepth that are treated as bugs.
60 using System.Collections;
61 using System.ComponentModel;
63 using System.Drawing.Imaging;
64 using System.Runtime.InteropServices;
66 namespace System.Windows.Forms
68 [DefaultProperty("Images")]
69 [Designer("System.Windows.Forms.Design.ImageListDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
70 [ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow)]
71 [TypeConverter("System.Windows.Forms.ImageListConverter, " + Consts.AssemblySystem_Windows_Forms)]
72 public sealed class ImageList : System.ComponentModel.Component
74 #region Private Fields
75 private EventHandler recreateHandle;
76 private readonly ImageCollection images;
77 #endregion // Private Fields
80 [Editor("System.Windows.Forms.Design.ImageCollectionEditor, " + Consts.AssemblySystem_Design, typeof(System.Drawing.Design.UITypeEditor))]
81 public sealed class ImageCollection : IList, ICollection, IEnumerable
83 private const int AlphaMask = unchecked((int)0xFF000000);
85 [StructLayout(LayoutKind.Explicit)]
86 private struct ArgbColor
106 class IndexedColorDepths
109 private IndexedColorDepths()
113 internal static readonly ArgbColor[] Palette4Bit;
114 internal static readonly ArgbColor[] Palette8Bit;
115 private static readonly int[] squares;
117 static IndexedColorDepths()
124 bitmap = new Bitmap(1, 1, PixelFormat.Format4bppIndexed);
125 palette = bitmap.Palette.Entries;
128 Palette4Bit = new ArgbColor[count = palette.Length];
129 for (index = 0; index < count; index++)
130 Palette4Bit[index].Argb = palette[index].ToArgb();
132 bitmap = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
133 palette = bitmap.Palette.Entries;
136 Palette8Bit = new ArgbColor[count = palette.Length];
137 for (index = 0; index < count; index++)
138 Palette8Bit[index].Argb = palette[index].ToArgb();
140 squares = new int[511];
141 for (index = 0; index < 256; index++)
142 squares[255 + index] = squares[255 - index] = index * index;
145 internal static int GetNearestColor(ArgbColor[] palette, int color)
156 count = palette.Length;
157 for (index = 0; index < count; index++)
158 if (palette[index].Argb == color)
161 red = unchecked((int)(unchecked((uint)color) >> 16) & 0xFF);
162 green = unchecked((int)(unchecked((uint)color) >> 8) & 0xFF);
164 nearestColor = AlphaMask;
165 minDistance = int.MaxValue;
167 for (index = 0; index < count; index++)
168 if ((distance = squares[255 + palette[index].Red - red] + squares[255 + palette[index].Green - green] + squares[255 + palette[index].Blue - blue]) < minDistance) {
169 nearestColor = palette[index].Argb;
170 minDistance = distance;
178 #region ImageCollection Private Fields
179 private ColorDepth colorDepth = ColorDepth.Depth8Bit;
180 private Color transparentColor = Color.Transparent;
181 private Size imageSize = new Size(16, 16);
182 private bool handleCreated;
183 private readonly ArrayList list = new ArrayList();
184 private readonly ImageList owner;
185 #endregion // ImageCollection Private Fields
187 #region ImageCollection Internal Constructors
188 // For use in ImageList
189 internal ImageCollection(ImageList owner)
193 #endregion // ImageCollection Internal Constructor
195 #region ImageCollection Internal Instance Properties
196 // For use in ImageList
197 internal ColorDepth ColorDepth {
199 return this.colorDepth;
203 if (!Enum.IsDefined(typeof(ColorDepth), value))
204 throw new InvalidEnumArgumentException("value", (int)value, typeof(ColorDepth));
206 if (this.colorDepth != value) {
207 this.colorDepth = value;
210 owner.OnRecreateHandle();
216 // For use in ImageList
217 internal IntPtr Handle {
219 this.handleCreated = true;
224 // For use in ImageList
225 internal bool HandleCreated {
227 return this.handleCreated;
231 // For use in ImageList
232 internal Size ImageSize {
234 return this.imageSize;
238 if (value.Width < 1 || value.Width > 256 || value.Height < 1 || value.Height > 256)
239 throw new ArgumentException("ImageSize.Width and Height must be between 1 and 256", "value");
241 if (this.imageSize != value) {
242 this.imageSize = value;
245 owner.OnRecreateHandle();
251 // For use in ImageList
252 internal ImageListStreamer ImageStream {
254 return list.Count == 0 ? null : new ImageListStreamer(this);
259 Image[] streamImages;
263 this.handleCreated = false;
267 else if ((streamImages = value.Images) != null) {
268 this.handleCreated = true;
271 for (index = 0; index < streamImages.Length; index++)
272 list.Add((Image)streamImages[index].Clone());
274 this.imageSize = value.ImageSize;
275 this.colorDepth = value.ColorDepth;
277 // Event is raised even when handle was not created yet.
278 owner.OnRecreateHandle();
284 // For use in ImageList
285 internal Color TransparentColor {
287 return this.transparentColor;
291 this.transparentColor = value;
294 #endregion // ImageCollection Internal Instance Properties
296 #region ImageCollection Public Instance Properties
306 return list.Count == 0;
310 public bool IsReadOnly {
317 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
318 public Image this[int index] {
320 return (Image)GetImage(index).Clone();
324 if (index < 0 || index >= list.Count)
325 throw new ArgumentOutOfRangeException("index");
327 list[index] = CreateImage(value, this.transparentColor);
330 #endregion // ImageCollection Public Instance Properties
332 #region ImageCollection Private Instance Methods
333 private Image CreateImage(Image value, Color transparentColor)
339 ImageAttributes imageAttributes;
342 throw new ArgumentNullException("value");
344 if (!(value is Bitmap))
345 throw new ArgumentException("Image must be a Bitmap.");
347 if (transparentColor.A == 0)
348 imageAttributes = null;
350 imageAttributes = new ImageAttributes();
351 imageAttributes.SetColorKey(transparentColor, transparentColor);
354 bitmap = new Bitmap(width = this.imageSize.Width, height = this.imageSize.Height, PixelFormat.Format32bppArgb);
355 graphics = Graphics.FromImage(bitmap);
356 graphics.DrawImage(value, new Rectangle(0, 0, width, height), 0, 0, value.Width, value.Height, GraphicsUnit.Pixel, imageAttributes);
359 return ReduceColorDepth(bitmap);
362 private unsafe Image ReduceColorDepth(Bitmap bitmap)
372 BitmapData bitmapData;
375 if (this.colorDepth < ColorDepth.Depth32Bit) {
376 bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
378 linePtr = (byte*)bitmapData.Scan0;
379 height = bitmapData.Height;
380 widthBytes = bitmapData.Width << 2;
381 stride = bitmapData.Stride;
383 if (this.colorDepth < ColorDepth.Depth16Bit) {
384 palette = this.colorDepth < ColorDepth.Depth8Bit ? IndexedColorDepths.Palette4Bit : IndexedColorDepths.Palette8Bit;
386 for (line = 0; line < height; line++) {
387 lineEndPtr = linePtr + widthBytes;
388 for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
389 *(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : IndexedColorDepths.GetNearestColor(palette, pixel | AlphaMask);
393 else if (this.colorDepth < ColorDepth.Depth24Bit) {
394 for (line = 0; line < height; line++) {
395 lineEndPtr = linePtr + widthBytes;
396 for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
397 *(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : (pixel & 0x00F8F8F8) | AlphaMask;
402 for (line = 0; line < height; line++) {
403 lineEndPtr = linePtr + widthBytes;
404 for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
405 *(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : pixel | AlphaMask;
411 bitmap.UnlockBits(bitmapData);
417 #endregion // ImageCollection Private Instance Methods
419 #region ImageCollection Internal Instance Methods
420 // For use in ImageList
421 internal Image GetImage(int index)
423 if (index < 0 || index >= list.Count)
424 throw new ArgumentOutOfRangeException("index");
426 return (Image)list[index];
429 // For use in ImageListStreamer
430 internal Image[] ToArray()
432 Image[] images = new Image[list.Count];
437 #endregion // ImageCollection Internal Instance Methods
439 #region ImageCollection Public Instance Methods
440 public void Add(Icon value)
448 throw new ArgumentNullException("value");
450 this.handleCreated = true;
452 bitmap = new Bitmap(width = this.imageSize.Width, height = this.imageSize.Height, PixelFormat.Format32bppArgb);
453 graphics = Graphics.FromImage(bitmap);
454 graphics.DrawIcon(value, new Rectangle(0, 0, width, height));
457 list.Add(ReduceColorDepth(bitmap));
460 public void Add(Image value)
462 Add(value, this.transparentColor);
465 public int Add(Image value, Color transparentColor)
467 this.handleCreated = true;
468 return list.Add(CreateImage(value, transparentColor));
471 public int AddStrip(Image value)
481 ImageAttributes imageAttributes;
484 throw new ArgumentNullException("value");
486 if ((imageWidth = value.Width) == 0 || (imageWidth % (width = this.imageSize.Width)) != 0)
487 throw new ArgumentException("Width of image strip must be a positive multiple of ImageSize.Width.", "value");
489 if (value.Height != (height = this.imageSize.Height))
490 throw new ArgumentException("Height of image strip must be equal to ImageSize.Height.", "value");
492 if (!(value is Bitmap))
493 throw new ArgumentException("Image must be a Bitmap.");
495 this.handleCreated = true;
497 imageRect = new Rectangle(0, 0, width, height);
498 if (this.transparentColor.A == 0)
499 imageAttributes = null;
501 imageAttributes = new ImageAttributes();
502 imageAttributes.SetColorKey(this.transparentColor, this.transparentColor);
506 for (imageX = 0; imageX < imageWidth; imageX += width) {
507 bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
508 graphics = Graphics.FromImage(bitmap);
509 graphics.DrawImage(value, imageRect, imageX, 0, width, height, GraphicsUnit.Pixel, imageAttributes);
512 list.Add(ReduceColorDepth(bitmap));
523 public bool Contains(Image image)
525 throw new NotSupportedException();
529 public IEnumerator GetEnumerator()
531 Image[] images = new Image[list.Count];
534 for (index = 0; index < images.Length; index++)
535 images[index] = (Image)((Image)list[index]).Clone();
537 return images.GetEnumerator();
540 public int IndexOf(Image image)
542 throw new NotSupportedException();
545 public void Remove(Image image)
547 throw new NotSupportedException();
550 public void RemoveAt(int index)
552 if (index < 0 || index >= list.Count)
553 throw new ArgumentOutOfRangeException("index");
555 list.RemoveAt(index);
557 #endregion // ImageCollection Public Instance Methods
559 #region ImageCollection Interface Properties
560 object IList.this[int index] {
566 if (!(value is Image))
567 throw new ArgumentException("value");
569 this[index] = (Image)value;
573 bool IList.IsFixedSize {
579 bool ICollection.IsSynchronized {
585 object ICollection.SyncRoot {
590 #endregion // ImageCollection Interface Properties
592 #region ImageCollection Interface Methods
593 int IList.Add(object value)
597 if (!(value is Image))
598 throw new ArgumentException("value");
601 this.Add((Image)value);
605 bool IList.Contains(object value)
607 return value is Image ? this.Contains((Image)value) : false;
610 int IList.IndexOf(object value)
612 return value is Image ? this.IndexOf((Image)value) : -1;
615 void IList.Insert(int index, object value)
617 throw new NotSupportedException();
620 void IList.Remove(object value)
623 this.Remove((Image)value);
626 void ICollection.CopyTo(Array array, int index)
630 for (imageIndex = 0; imageIndex < this.Count; imageIndex++)
631 array.SetValue(this[index], index++);
633 #endregion // ImageCollection Interface Methods
635 #endregion // Sub-classes
637 #region Public Constructors
640 images = new ImageCollection(this);
643 public ImageList(System.ComponentModel.IContainer container) : this()
647 #endregion // Public Constructors
649 private void OnRecreateHandle()
651 if (recreateHandle != null)
652 recreateHandle(this, EventArgs.Empty);
655 #region Public Instance Properties
656 [DefaultValue(ColorDepth.Depth8Bit)]
657 public ColorDepth ColorDepth {
659 return images.ColorDepth;
663 images.ColorDepth = value;
668 [EditorBrowsable(EditorBrowsableState.Advanced)]
669 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
670 public IntPtr Handle {
672 return images.Handle;
677 [EditorBrowsable(EditorBrowsableState.Advanced)]
678 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
679 public bool HandleCreated {
681 return images.HandleCreated;
686 [MergableProperty(false)]
687 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
688 public ImageCollection Images {
695 public Size ImageSize {
697 return images.ImageSize;
701 images.ImageSize = value;
707 [EditorBrowsable(EditorBrowsableState.Advanced)]
708 public ImageListStreamer ImageStream {
710 return images.ImageStream;
714 images.ImageStream = value;
718 public Color TransparentColor {
720 return images.TransparentColor;
724 images.TransparentColor = value;
727 #endregion // Public Instance Properties
729 #region Public Instance Methods
730 public void Draw(Graphics g, Point pt, int index)
732 this.Draw(g, pt.X, pt.Y, index);
735 public void Draw(Graphics g, int x, int y, int index)
737 g.DrawImage(images.GetImage(index), x, y);
740 public void Draw(Graphics g, int x, int y, int width, int height, int index)
742 g.DrawImage(images.GetImage(index), x, y, width, height);
745 public override string ToString()
747 return base.ToString() + " Images.Count: " + images.Count.ToString() + ", ImageSize: " + images.ImageSize.ToString();
749 #endregion // Public Instance Methods
751 #region Protected Instance Methods
752 protected override void Dispose(bool disposing)
754 base.Dispose(disposing);
756 #endregion // Protected Instance Methods
760 [EditorBrowsable(EditorBrowsableState.Advanced)]
761 public event EventHandler RecreateHandle {
763 recreateHandle += value;
767 recreateHandle -= value;