2012-02-22 60 views
0

我写了一个小应用程序,将在我的工作环境中用于裁剪图像。包含图像的窗体(.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函数是好的 - 它的工作原理是,如果我使用表单作为选择区域,但使用矩形会使爵士音乐有点过分。

回答

0

有趣的是,这是因为主要形式,并且控制该图像是在与在所述形式分离的顶部的工具栏之间的空间的控制和主窗体的顶部。为了解决这个问题,我只是在捕捉画面修改一个行来说明这些像素,如下图所示:

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

干杯

1

您已经检索到屏幕的相对位置为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); 
} 
+0

嗯,它仍然抓住了错误的区域,Y坐标+ 50的某些原因。 – 2012-02-23 07:58:20

+0

哦,你的代码中的Point被命名为'relativePosition',但是你可以将它作为ptRelativePosition来引用 - 只是你知道的。 – 2012-02-23 08:03:07

+0

@AdLib:你可以上传一个项目什么的? (对于迟到的回复,由于某种原因,我没有收到评论通知。) – Ryan 2012-02-23 14:35:48