2012-02-22 54 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