简体   繁体   中英

How to detect a click on irregular image drawn on a panel

actually i am drawing an image on a panel.the image was in irrigular shape. For a mouse click i want to display a message wheather the click was done on the image or on the panel.

You can use Region Class and its Intersect Method in order to achieve your goal, but probably there exist better solutions. However, until you found them, try the following one based on the example of capturing mouse point in ellipse drawed on the panel.

Declare fields:

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

Initialize above fields:

_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.

Panel paint event handle:

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

Panel mouse down event handle:

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");
}

Below is scenario for drawing just image on a panel:

Declare fields:

private readonly Bitmap _image;
private readonly Graphics _panelGraphics;

Initialize fields:

_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();

Panel paint event handle:

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

Panel mouse down event handle:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM