简单的Demo,可以用于学习Image的处理、winform里的拖动事件,也可以用于广大学生党的作业 (其实这就是帮学生党解决的作业,只不过后来又调整了下……),因为是Demo,所以代码也就随便了些,下面是运行时的截图,弄个妹子赏眼点,游戏方式就是将随机打乱的图片拖动到待拼图区域,如果位置一致时,在鼠标松开,图片就会被绘制到待拼图区域,同时在随机打乱的图片中移除这一块区域
首先是图片相关的部分:图片等比例缩放+分割,以下是相关代码
public static class Helpers
{
/// <summary>
/// 获取等比例缩放的图片(高宽不一致时获取最中间部分的图片)
/// </summary>
/// <param name="fromImage"></param>
/// <param name="width">要获取的宽度</param>
/// <param name="height">要获取的高度</param>
/// <returns></returns>
public static Image AdjImageToFitSize(this Image fromImage, int width, int height)
{
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
Point point = new Point(0, 0);
Point point2 = new Point(width, 0);
Point point3 = new Point(0, height);
Point[] destPoints = new Point[] { point, point2, point3 };
Rectangle rect = GetImageRectangle(fromImage);
graphics.DrawImage(fromImage, destPoints, rect, GraphicsUnit.Pixel);
Image image = Image.FromHbitmap(bitmap.GetHbitmap());
bitmap.Dispose();
graphics.Dispose();
return image;
}
private static Rectangle GetImageRectangle(Image fromImage)
{//居中位置获取
int x = 0;
int y = 0;
int height = fromImage.Height;
int width = fromImage.Width;
if (fromImage.Height > fromImage.Width)
{
height = fromImage.Width;
y = (fromImage.Height - fromImage.Width) / 2;
}
else
{
width = fromImage.Height;
x = (fromImage.Width - fromImage.Height) / 2;
}
return new Rectangle(x, y, width, height);
}
/// <summary>
/// 将图片切割成小图片,图片顺序为先水平后垂直
/// </summary>
/// <param name="fromImage"></param>
/// <param name="cx">x方向切割数</param>
/// <param name="cy">y方向切割数</param>
/// <returns></returns>
public static Image[] SplitToSmallImages(this Image fromImage, int cx, int cy)
{
Image[] imgs = new Image[cx * cy];
int nWidth = fromImage.Width / cx;
int nHeight = fromImage.Height / cy;
Bitmap image = new Bitmap(nWidth, nHeight);
Graphics graphics = Graphics.FromImage(image);
for (int i = 0; i < cy; i++)
{
for (int j = 0; j < cx; j++)
{
graphics.DrawImage(fromImage, 0, 0, new Rectangle(j * nWidth, i * nHeight, nWidth, nHeight), GraphicsUnit.Pixel);
Image img = Image.FromHbitmap(image.GetHbitmap());
int idx = j + i * cx;
img.Tag = idx;
imgs[idx] = img;
}
}
return imgs;
}
}
然后各种点击、拖动交互的就不多说了,可以自行去下载代码后查看,因为图片分割的时候是分割成了一维数组,这里就说下如何根据索引编号获取对应的二维数组,下面是相关代码片段,上面的代码中在切割图片时已经采用了先水平后垂直的方式,那根据索引获取二维位置也就只要这样就行了,即水平位置的计算方式为 索引号%每行分割块数,垂直位置的计算方式为 索引号/每行分割块数,当然下面的代码中不是通过索引来获取x,y进行对比,而是根据x,y获取对应索引
int idx = (int)e.Data.GetData(typeof(int));
Point p = this.pnl_DragOn.PointToClient(new Point(e.X, e.Y));
int x = p.X / this.SideLength;//计算x方向上的位置
int y = p.Y / this.SideLength;//计算y方向上的位置
if (idx == x + this.ImgNumbers * y)//判断图片位置是否与计算出来的位置一致
{
Graphics graphics = this.pnl_DragOn.CreateGraphics();
graphics.DrawImage(this._dragPic.Image, x * this.SideLength, y * this.SideLength);
this._dragPic.Image = null;//图片放置后,移除Box上的Image
if (!this._splitPictureBoxes.Any(pb => pb.Image != null))
{
MessageBox.Show("恭喜你,图片拼好了");
}
}
源码下载,在Program.cs里面Application.Run(new RandomPictureForm1())运行即为此博客对应Demo