捕获矩形后面的图像

我写了一个小应用程序,它将在我的工作环境中用于裁剪图像。 包含图像的窗体(.NET 3.5)有一个透明的矩形,我用它来拖动图像的一部分并点击一个按钮来获取矩形后面的任何内容。

目前我正在使用下面的代码,这导致我的问题,因为它捕获的区域偏离了几个像素,我认为这与我的CopyFromScreen函数有关。

//Pass in a rectangle private void SnapshotImage(Rectangle rect) { Point ptPosition = new Point(rect.X, rect.Y); Point ptRelativePosition; //Get me the screen coordinates, so that I get the correct area ptRelativePosition = PointToScreen(ptPosition); //Create a new bitmap Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb); //Sort out getting the image Graphics g = Graphics.FromImage(bmp); //Copy the image from screen g.CopyFromScreen(this.Location.X + ptPosition.X, this.Location.Y + ptPosition.Y, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy); //Change the image to be the selected image area imageControl1.Image.ChangeImage(bmp); } 

如果有人能够发现为什么当图像被重新绘制时,我会在这一点上永远感激。 此外, ChangeImage函数很好 – 如果我使用一个表单作为选择区域但是使用一个矩形可以让一些东西变得有趣。

您已经以ptRelativePosition检索了屏幕的相对位置,但实际上并没有使用它 – 您将矩形的位置添加到表单的位置,而不考虑表单的边框。

这是固定的,有一些优化:

 // Pass in a rectangle private void SnapshotImage(Rectangle rect) { // Get me the screen coordinates, so that I get the correct area Point relativePosition = this.PointToScreen(rect.Location); // Create a new bitmap Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb); // Copy the image from screen using(Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(relativePosition, Point.Empty, bmp.Size); } // Change the image to be the selected image area imageControl1.Image.ChangeImage(bmp); } 

有趣的是,这是因为图像所在的主窗体和控件之间的空间以及窗体顶部的工具栏将控件和主窗体的顶部分开。 为了解决这个问题,我只需修改捕获屏幕中的一行来计算这些像素,如下所示:

 g.CopyFromScreen(relativePosition.X + 2, relativePosition.Y+48, Point.Empty.X, Point.Empty.Y, bmp.Size); 

干杯