Search code examples
c#winformspictureboxregions

Delete transparent background from picturebox in winforms c#


I want to get the x,y location on click over a picturebox.I have 2 pictureboxes and one is over the other.The small picturebox has a transparent region background(.png). I want to get the second's picturebox when I click on this area.

this is the code getting the x,y position:

  pictureBox2.MouseClick += (s, e) =>
        {
            if (e.Button == MouseButtons.Right)
            {
                MessageBox.Show(String.Format("Right Clicked2 at X: {0} Y: {1}", e.X, e.Y));
            }
            else if (e.Button == MouseButtons.Left)
            { MessageBox.Show(String.Format("Mouse Clicked2 at X: {0} Y: {1}", e.X, e.Y)); }
        };

        pictureBox1.MouseClick += (s, e) =>
        {
            if (e.Button == MouseButtons.Right)
            {
                MessageBox.Show(String.Format("Right Clicked at X: {0} Y: {1}", e.X, e.Y));
            }
            else if (e.Button == MouseButtons.Left)
            { MessageBox.Show(String.Format("Mouse Clicked at X: {0} Y: {1}", e.X, e.Y)); }
        };

enter image description here

with this code the second image shown(good showing).But when I cleck to the transparent area it gives me the message from the picturebox2 and not the picturebox1.Any idea how can assign this area to picturebox1?

     var pos = this.PointToScreen(pictureBox2.Location);
        pos = pictureBox1.PointToClient(pos);
        pictureBox2.Parent = pictureBox1;
        pictureBox2.Location = pos;
        pictureBox2.BackColor = Color.Transparent;

enter image description here


Solution

  • Just use one picturebox and see if you are inside this area. The area is a semi cycle with center x0, 0. So calculate the

    squareroot(y*y + (x0-x)*(x0-x)), x,y is where you click. 
    

    If it is smaller from the radius you are inside otherwise outside.

    Edit.

    Create a graphic path

    using System.Drawing.Drawing2D; //is needed for the graphics path
    
    GraphicsPath gp = new GraphicsPath();
    
    gp.AddEllipse (x, y, width, height); //x,y the upper left corner of the rect containing the ellipse
    
    if( gp.IsVisible (e.X, e.Y) ){
        //is inside
    }
    else{
        //is outside
    }
    

    Note: The y coordinate will be negative

    valter