Lidia
Lidia

Reputation: 33

How to draw an image by pressing a button in WinForms?

I have to do this editor (BPMN editor) and I'm stuck.I have this button in the Form with an image on it and I want this: when I click the button and then I press click on my canvas (the draw area) to put the image from the button there.

Upvotes: 2

Views: 2334

Answers (1)

Navid Farhadi
Navid Farhadi

Reputation: 3467

public class Shape
{
    public float X { get; set; }
    public float Y { get; set; }
    public Image Image { get; set; }
}

and the code:

    private string _currentTool;
    private readonly List<Shape> _shapes;

    private void Button1Click(object sender, EventArgs e)
    {
        _currentTool = "img";
    }

    private void PictureBox1MouseDown(object sender, MouseEventArgs e)
    {
        switch (_currentTool)
        {
            case "img":
                _shapes.Add(new Shape {Image = button1.Image, X = e.X, Y = e.Y});
                pictureBox1.Invalidate();
                break;
        }
    }

    private void PictureBox1Paint(object sender, PaintEventArgs e)
    {
        foreach (var shape in _shapes)
        {
            e.Graphics.DrawImage(shape.Image, shape.X, shape.Y);
        }
    }

Upvotes: 3

Related Questions