2011-05-22 103 views
2

我是新來的c#。我在picturebox上有一個圖像,我想在圖像上繪製一個矩形,以捕獲我將繪製的矩形的X,Y座標和寬度/高度(對照圖片框上的圖像)。我知道我必須在pictureBox1_MouseEnter..etc上做點什麼。但我不知道從哪裏開始。如何捕獲PictureBox上的鼠標座標?

private void pictureBox1_MouseEnter(object sender, EventArgs e) 
    { 

     Rectangle Rect = RectangleToScreen(this.ClientRectangle); 
    } 

如果任何人能給我示例代碼,我將不勝感激。

謝謝。

回答

12

你不想使用MouseEnter可言。您想使用MouseDown,因爲您不想開始跟蹤用戶繪製的矩形,直到他們單擊鼠標按鈕。

所以在MouseDown事件處理函數方法中,保存遊標的當前座標。這是矩形的起始位置,點(X,Y)。

private Point initialMousePos; 

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    this.initialMousePos = e.Location; 
} 

,然後在MouseUp event,當用戶停止拖動並釋放鼠標按鍵被提出,要保存鼠標光標的最後終點,並結合起來,與最初的出發點建立一個矩形。建立這樣一個矩形的最簡單方法是使用Rectangle classFromLTRB靜態方法:

private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
{ 
    // Save the final position of the mouse 
    Point finalMousePos = e.Location; 

    // Create the rectangle from the two points 
    Rectangle drawnRect = Rectangle.FromLTRB(
              this.initialMousePos.X, 
              this.initialMousePos.Y, 
              finalMousePos.X, 
              finalMousePos.Y); 

    // Do whatever you want with the rectangle here 
    // ... 
} 

你可能想在MouseMove事件處理方法與一些繪畫代碼此相結合,給用戶一個視覺指示他們在繪製時繪製的矩形。

方式做,這是處理MouseMove event得到鼠標的當前位置,然後調用Invalidate方法,這將提高Paint event。您的所有繪畫代碼應該位於Paint事件處理程序中。這是比你在網上找到的很多樣本更好的方法,你會在MouseMove事件處理程序方法中看到類似CreateGraphics的內容。如果可能,避免這種情況。

樣品實施:

private Point currentMousePos; 

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
{ 
    // Save the current position of the mouse 
    currentMousePos = e.Location; 

    // Force the picture box to be repainted 
    pictureBox1.Invalidate(); 
} 

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    // Create a pen object that we'll use to draw 
    // (change these parameters to make it any color and size you want) 
    using (Pen p = new Pen(Color.Blue, 3.0F)) 
    { 
     // Create a rectangle with the initial cursor location as the upper-left 
     // point, and the current cursor location as the bottom-right point 
     Rectangle currentRect = Rectangle.FromLTRB(
                this.initialMousePos.X, 
                this.initialMousePos.Y, 
                currentMousePos.X, 
                currentMousePos.Y); 

     // Draw the rectangle 
     e.Graphics.DrawRectangle(p, currentRect); 
    } 
} 

幾件事情需要注意這個代碼,如果你從來沒有做過任何類型的畫前。第一件事是我在using statement中包裝了Pen object(我們用來做實際製圖)的創建。每當您創建一個實現IDisposable interface的對象(如畫筆和筆)以防止應用程序中發生內存泄漏時,這是很好的一般練習。

此外,PaintEventArgs爲我們提供了一個Graphics class的實例,它將所有基本繪圖功能封裝在.NET應用程序中。所有你所要做的就是調用的方法,如對類實例DrawRectangleDrawImage,通過在適當的對象作爲參數,而所有的圖紙被自動完成的。很簡單,對嗎?

最後,請注意,我們所做的正是這裏同樣的事情來創建一個矩形,因爲我們在MouseUp事件處理方法,最終做到。這很有意義,因爲我們只是想在用戶創建矩形時獲得矩形的即時大小。

+0

感謝科迪,你的代碼工作正常,你介意給我快速繪畫樣本? – Kelly 2011-05-22 10:46:17

+0

@Kelly:用繪畫樣本更新。不知道你在.NET世界中對這種類型的事物有多熟悉,所以我試圖儘可能地解釋它。如果您有任何問題,請留下評論! – 2011-05-22 10:58:18