在图片框中显示图标
我想在图片框中显示icon file
。 我正在使用此代码来设置图像。
pictureBox1.Image = new Icon(openFileDialog.FileName, new Size(48, 48)).ToBitmap();
但我得到了这个例外。
System.ArgumentOutOfRangeException: Requested range extends past the end of the array. at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length) at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length) at System.Drawing.Icon.ToBitmap()
如何克服这个问题?
谢谢。
解决了这个问题。
pictureBox1.Image = Bitmap.FromHicon(new Icon(openFileDialog.FileName, new Size(48, 48)).Handle);
某些图标的大小不正确48×48到32×32。
我的最终代码是:
Bitmap _image; try { _image = new Icon(icon, width, height).ToBitmap(); } catch(ArgumentOutOfRangeException) { _image = Bitmap.FromHicon(new Icon(icon, new Size(width, height)).Handle); }
有时Bitmap.FromHicon
不能完美转换。 我找到另一个解决方案
// event Paint of pictureBox1 void pictureBox1_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawIcon(theIcon, 0, 0); }