[英]How to detect a click on irregular image drawn on a panel
實際上我在panel.image上繪制圖像是不規則的形狀。 單擊鼠標后,我想顯示一條消息,單擊已在圖像或面板上完成。
您可以使用Region Class及其相交方法來實現您的目標,但是可能存在更好的解決方案。 但是,直到找到它們為止,以捕獲面板上繪制的橢圓形鼠標點為例,嘗試以下一種方法。
聲明字段:
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");
}
以下是在面板上僅繪制圖像的方案:
聲明字段:
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.