最近写一个小程序,要将很多图片随机显示在屏幕上(不限次数),一开始是想在线程中死循环执行,后来错太多改成了在time控件上的事件上执行。问题开始了
1.p.Load("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\img\\image\\xiao.gif");
这是最开始的代码,报错GDI+ 中发生一般性错误s,一看懵了,这是啥子错误没见过啊,后来查了一下
PictureBox p = new PictureBox();
string aa = "D:\\imgs\\img\\image\\2.gif";
string bb = "D:\\imgs\\img\\0.jpg";
//p.Load("C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\img\\image\\xiao.gif");
Random r = new Random();
int x = X;
int y = r.Next(X);
Console.WriteLine(x + "=======" + x);
p.Location = InitPoint();
Bitmap bmp = null;
if (i % 2 == 0)
{
bmp = new Bitmap(aa);
}
else
{
bmp = new Bitmap(bb);
}
//新建第二个bitmap类型的bmp2变量,我这里是根据我的程序需要设置的。
Bitmap bmp2 = new Bitmap(400, 400, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
//将第一个bmp拷贝到bmp2中
Graphics draw = Graphics.FromImage(bmp2);
draw.DrawImage(bmp, 0, 0);
p.Image = (Image)bmp2;//读取bmp2到picturebox
draw.Dispose();
bmp.Dispose();
this.Controls.Add(p);
改成这样就不报错了。
后来在设置图片的坐标时利用随机数生成却发现生成的都是对角线坐标
后来在博客园里看到一段代码解决了问题http://www.cnblogs.com/hl_blog/archive/2010/09/02/1815925.html
private Point InitPoint()
{
Point p = new Point();
Rectangle ScreenArea = System.Windows.Forms.Screen.GetBounds(this);
int width1 = ScreenArea.Width; //屏幕宽度
int height1 = ScreenArea.Height; //屏幕高度
int x, y;
long tick = DateTime.Now.Ticks;
Random pointX = new Random(GetRandomSeed());
Random pointY = new Random(GetRandomSeed());
x = pointX.Next(0, width1 - 50);
y = pointY.Next(0, height1 - 50);
p = new Point(x, y);
return p;
}
/// <summary>
/// 随机生成种子数(摘抄)
/// </summary>
/// <returns></returns>
static int GetRandomSeed()
{
byte[] bytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}