读书人

imagelist.images[零].tag无法赋值

发布时间: 2013-03-01 18:33:02 作者: rapoo

imagelist.images[0].tag无法赋值
imageList1.Images[0].Tag = "000";
MessageBox.Show(imageList1.Images[0].Tag.ToString());//出错!!!

注:已经为imagelist1添加了几张图片。
错误信息为:未将对象引用设置到对象的实例。

[解决办法]
在ImageList中获取某索引处的图片是创建新图,因此设置Tag无效,每次访问该属性得到的都是不同的Image对象,为什么每次都要创建新图而不是缓存图片就不知道了。

public sealed class ImageList : Component
{
private ImageList owner;

public Image this[int index]
{
get
{
if ((index < 0)
[解决办法]
(index >= this.Count))
{
throw new ArgumentOutOfRangeException("index", SR.GetString("InvalidArgument", new object[] { "index", index.ToString(CultureInfo.CurrentCulture) }));
}
return this.owner.GetBitmap(index);
}
set ......
}
......
}

下面是GetBitmap方法的具体代码:
private Bitmap GetBitmap(int index)
{
if ((index < 0)
[解决办法]
(index >= this.Images.Count))
{
throw new ArgumentOutOfRangeException("index", SR.GetString("InvalidArgument", new object[] { "index", index.ToString(CultureInfo.CurrentCulture) }));
}
Bitmap image = null;
if (this.ColorDepth == ColorDepth.Depth32Bit)
{
NativeMethods.IMAGEINFO pImageInfo = new NativeMethods.IMAGEINFO();
if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, pImageInfo))
{
Bitmap bitmap2 = null;
BitmapData bmpData = null;
BitmapData targetData = null;
IntSecurity.ObjectFromWin32Handle.Assert();
try
{
bitmap2 = Image.FromHbitmap(pImageInfo.hbmImage);


bmpData = bitmap2.LockBits(new Rectangle(pImageInfo.rcImage_left, pImageInfo.rcImage_top, pImageInfo.rcImage_right - pImageInfo.rcImage_left, pImageInfo.rcImage_bottom - pImageInfo.rcImage_top), ImageLockMode.ReadOnly, bitmap2.PixelFormat);
int stride = bmpData.Stride;
int height = this.imageSize.Height;
if (BitmapHasAlpha(bmpData))
{
image = new Bitmap(this.imageSize.Width, this.imageSize.Height, PixelFormat.Format32bppArgb);
targetData = image.LockBits(new Rectangle(0, 0, this.imageSize.Width, this.imageSize.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
this.CopyBitmapData(bmpData, targetData);
}
}
finally
{
CodeAccessPermission.RevertAssert();
if (bitmap2 != null)
{
if (bmpData != null)
{
bitmap2.UnlockBits(bmpData);
}
bitmap2.Dispose();
}
if ((image != null) && (targetData != null))
{
image.UnlockBits(targetData);
}
}
}
}
if (image == null)
{
image = new Bitmap(this.imageSize.Width, this.imageSize.Height);


using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
SafeNativeMethods.ImageList_DrawEx(new HandleRef(this, this.Handle), index, new HandleRef(graphics, hdc), 0, 0, this.imageSize.Width, this.imageSize.Height, -1, -1, 1);
}
finally
{
graphics.ReleaseHdcInternal(hdc);
}
}
}
image.MakeTransparent(fakeTransparencyColor);
return image;
}


微软是哪根筋不对我就不知道了,还不如自己创建静态变量列表存放图片呢,那样效率更高。

读书人网 >C#

热点推荐