2013-02-25 56 views

回答

0

您可以使用Region Class及其Intersect Method爲了實現您的目標,但可能存在更好的解決方案。但是,在找到它們之前,請根據在面板上繪製的橢圓捕獲鼠標點的示例嘗試以下步驟。

聲明字段:

private readonly GraphicsPath _graphicsPath; 
private readonly Region _region; 
private readonly Graphics _panelGraphics; 

初始化上述字段:

_graphicsPath = new GraphicsPath(); 
_graphicsPath.AddEllipse(100, 100, 100, 100); // Path that contains simple ellipse. You can add here more shapes and combine them in similar manner as you draw them. 
_region = new Region(_graphicsPath); // Create region, that contains Intersect method. 
_panelGraphics = panel1.CreateGraphics(); // Graphics for the panel. 

面板漆事件句柄:

private void panel_Paint(object sender, PaintEventArgs e) 
{ 
    _panelGraphics.FillEllipse(Brushes.Red, 100, 100, 100, 100); // Draw your structure. 
} 

面板鼠標按下事件句柄:

private void panel_MouseDown(object sender, MouseEventArgs e) 
{ 
    var cursorRectangle = new Rectangle(e.Location, new Size(1, 1)); // We need rectangle for Intersect method. 
    var copyOfRegion = _region.Clone(); // Don't break original region. 
    copyOfRegion.Intersect(cursorRectangle); // Check whether cursor is in complex shape. 

    Debug.WriteLine(copyOfRegion.IsEmpty(_panelGraphics) ? "Miss" : "In"); 
} 
+0

對不起,說它沒有工作,我正在用一些縮放級別在apanel上繪製圖像,圖像不會覆蓋整個面板,所以如何檢測我的鼠標點擊是否完成圖像或面板中的其餘區域,plz幫助我.. – user2095270 2013-02-26 05:47:43

+0

@ user2095270:如果這只是您正在繪製的文件(不是您自己的草稿,繪圖)中的圖像,請使用我的第二個答案中的場景。在我的機器上檢查這個答案,它的工作原理,但只有當你繪製結構,你可以添加到* GraphicsPath *。 – 2013-02-26 07:45:49

0

下面是場景中的一個面板上繪製只圖像:

聲明字段:

private readonly Bitmap _image; 
private readonly Graphics _panelGraphics; 

初始化字段:

_image = new Bitmap(100, 100); // Image and panel have same size. 
var imageGraphics = Graphics.FromImage(_image); 
imageGraphics.FillEllipse(Brushes.Red, 10, 10, 50, 50); // Some irregular image. 

panel2.Size = new Size(100, 100); 
panel2.BackColor = Color.Transparent; // Panel's background color is transparent. 
_panelGraphics = panel2.CreateGraphics(); 

面板漆事件句柄:

private void panel_Paint(object sender, PaintEventArgs e) 
{ 
    _panelGraphics.DrawImageUnscaled(_image, 0, 0); 
} 

面板鼠標向下事件句柄:

private void panel_MouseDown(object sender, MouseEventArgs e) 
{ 
    Debug.WriteLine(_image.GetPixel(e.Location.X, e.Location.Y).A != 0 ? "In" : "Miss"); 
} 
+0

上面的場景要求,該面板的* BackColor *設置爲* Transparent *,並且圖像上不屬於該形狀的區域是透明的。 – 2013-02-26 07:47:33

相關問題