C# Windows form application development, I want to draw a straight line again while leaving the straight line I drew.

Asked 2 years ago, Updated 2 years ago, 58 views

We are currently developing Windows form applications.
The code description programming language is C#.
What we're doing at this point is we can draw a straight line connecting the two points by left-clicking the starting point of the straight line and left-clicking it again.
DrawLine method.
It is displayed in pictureBox.

What do you want to implement?
You can draw a straight line, but if you want to draw a figure by connecting lines and lines, you need to be able to draw multiple lines.
However, I didn't know if I should write the same description, so could someone help me?
Here's the source code:

using System;
using System.Collections;
using System.Collections.General;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Console;

public partial class Form 1:Form
{

    ///
    /// Define each variable, etc.
    ///

    // Variable to observe switch ON/OFF to implement function when button of type of line to draw is clicked
    private bool btnSolidWasClicked=false;

    // Define variables to select start point (lsp) and end point (lep) by left-clicking
    // MouseButtons.Left
    private Point lsp = new Point();
    private Point lep = new Point();
    // Determines whether it is true or false when left-clicking
    private Boolean lsp_flag;

    private void pictureBox1_MouseDown(object sender, MouseEventArgse)
    {
        if(btnSolidWasClicked)
        {
            // Create an Image object to draw to
            Bitmap canvas = new Bitmap (pictureBox1.Width, pictureBox1.Height);
            // Create Graphics Objects for Image Objects
            Graphics g=Graphics.FromImage(canvas);
            // Smooth the line
            g.SmoothingMode=SmoothingMode.AntiAlias;
            // Creating a Pen Object
            Pen GreenPen = new Pen (Color.White, 3);

            // The type of straight line is solid line
            GreenPen.DashStyle=DashStyle.Solid;

            // Display coordinates
            label1.Text=string.Format("Screen Position:{0:d}, {1:d}",
            Cursor.Position.X, Cursor.Position.Y);

            if(lsp_flag)//End Point Processing
            {
                lep = e.Location;
                g. DrawLine (GreenPen, lsp, lep);
                // Free up resources
                GreenPen.Dispose();
                g.Dispose();
                lsp_flag=false;
                // Displayed in Picture 1
                pictureBox1.Image=canvas;
            }
            else // Processing the starting point
            {
                lsp = e.Location;
                g.DrawRectangle (GreenPen, lsp.X, lsp.Y, 0.1f, 0.1f);
                // Free up resources
                GreenPen.Dispose();
                g.Dispose();
                lsp_flag = true;
                // Displayed in Picture 1
                pictureBox1.Image=canvas;
            }
        }
    }
}

c# visual-studio

2022-09-30 12:10

3 Answers

Simple Answer

Every time I click on the code in question, I create a white image with the code below, and I draw a line on it, so I can't write more than one straight line.
Bitmap canvas=new Bitmap (pictureBox1.Width, pictureBox1.Height);

Overwrite pictureBox1 without erasing the drawn line.
Rewrite pictureBox1_MouseDown as shown in sample 1.
However, if you reset the endpoint flag with lsp_flag=false; every time you write an endpoint, it will not be a continuous line segment.
In todo in sample 1, the lines are continuous with left click and the end point with right click.

private void pictureBox1_MouseDown(object sender, MouseEventArgse)
    {
        if(btnSolidWasClicked)
        {
            // Create a graphics object to draw to
            using(Graphics g=pictureBox1.CreateGraphics())
            // Creating a Pen Object
            using (Pen GreenPen = new Pen (Color.White, 3)
            {
                // Smooth the line
                g.SmoothingMode=SmoothingMode.AntiAlias;

                // The type of straight line is solid line
                GreenPen.DashStyle=DashStyle.Solid;

                // Display coordinates
                label1.Text=string.Format("Screen Position:{0:d}, {1:d}",
                Cursor.Position.X, Cursor.Position.Y);

                if(lsp_flag)//End Point Processing
                {
                    lep = e.Location;
                    g. DrawLine (GreenPen, lsp, lep);
                    lsp = lep;
                    // Todo Please make a separate decision as to whether it is the last stop or not.
                    // ↓ Example of determining the endpoint when right-clicking
                    if (e.Button==MouseButtons.Right)
                    {
                        lsp_flag=false;
                    }
                }
                else // Processing the starting point
                {
                    lsp = e.Location;
                    g.DrawRectangle (GreenPen, lsp.X, lsp.Y, 0.1f, 0.1f);
                    lsp_flag = true;
                }
            }
        }
    }

Applicable Answers

Simple answers cannot be processed such as "Undo processing to erase one line" or "Change the color of the line later."
If you're looking to enhance your experience as a paint software, you might want to create a class that holds the type, thickness, and color of the line you want to draw for each coordinate you click on and manage it in a list.
The DrawInfo class in Sample 2 is an example.
Assign the Paint event in pictureBox1 to PictureBox1_Paint if you wish to try.

using System;
using System.Collections.General;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form 1:Form
    {
        ///
        /// Define each variable, etc.
        ///

        // List to manage drawing locations
        private List <DrawInfo>DrawList=newList<DrawInfo>();
        // Variable to observe switch ON/OFF to implement function when button of type of line to draw is clicked
        private bool btnSolidWasClicked=false;
        // Determines whether it is true or false when left-clicking
        private Boolean lsp_flag;

        public Form 1()
        {
            InitializeComponent();
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgse)
        {
            DrawList.Add (new DrawInfo(e.Location, btnSolidWasClicked, lsp_flag);
            pictureBox1.Refresh();
            lsp_flag=(e.Button==MouseButtons.Right);
        }

        private void PictureBox1_Paint(object sender, PaintEventArgse)
        {
            if(DrawList.Count==0)return;
            using(var canvas=new Bitmap(pictureBox1.width, pictureBox1.Height))
            using (Graphics g=Graphics.FromImage(canvas))
            {
                g.SmoothingMode=SmoothingMode.AntiAlias;
                DrawInfo prev = null;
                foreach (var info in DrawList)
                {
                    info.Draw(g,prev);
                    prev = info;
                }
                // When canvas is set to Image, an exception occurs when it is dropped, so make a copy
                pictureBox1.Image=(Bitmap)canvas.Clone();
            }
        }
    }

    public class DrawInfo
    {
        public point location {get;set;}
        public Pen {get {return new Pen (PenColor, PenWidth);}}
        public Color PenColor {get;set;}
        public float PenWidth {get;set;}
        public DashStyle Style {get;set;}
        /// <summary>
        /// line segment start flag
        /// </summary>
        public bool IsStart {get;set;}

        protectedDrawInfo()
        {
            PenColor=Color.White;
            PenWidth = 3f;
            Style=DashStyle.Dot;
        }

        public DrawInfo (Point location, bool isSolid, bool isStart)
            : This()
        {
            Location = location;
            Style=isSolid?DashStyle.Solid:DashStyle.Dash;
            IsStart = isStart;
        }

        /// <summary>
        /// draw a line segment.draw a point as a starting point if there is no previous point
        /// </summary>
        /// <param name="g"></param>
        /// <param name="prev"></param>
        public void Draw (Graphics g, DrawInfo prev)
        {
            if(prev==null)
            {
                IsStart = true;
            }
            using(varpen=Pen)
            {
                if (IsStart)
                {
                    // Processing the starting point
                    var=(int) (PenWidth/2);
                    variable = new Rectangle
                    {
                        X = Location.X-r,
                        Y = Location.Y-r,
                        Width = r,
                        Height = r,
                    };
                    g. DrawElipse (pen, rect);
                }
                else
                {
                    // Line segment processing
                    g.DrawLine(pen,prev.Location,Location);
                }
            }
        }
    }

}


2022-09-30 12:10

I think you write on pictureBox in mouse down event, but not directly in mouse down event, remember the coordinates and do pictureBox.Refresh();
Then a Paint event will occur, so I will draw according to the coordinates I remember.


2022-09-30 12:10

Graphics objects were adopted without Image objects.Also, after drawing a line, I was able to draw multiple lines without any problems by adding updates to the starting point.
Below is an excerpt of the revised code.
Thank you for your reply.

private void pictureBox1_MouseDown(object sender, MouseEventArgse)
{
    if(btnSolidWasClicked)
    {
        // Create Graphics Object
        Graphics g=this.pictureBox1.CreateGraphics();

        g.SmoothingMode=SmoothingMode.AntiAlias;
        // Creating a Pen Object
        Pen GreenPen = new Pen (Color.White, 3);
        // solid line
        GreenPen.DashStyle=DashStyle.Solid;
        // Display coordinates
        label1.Text=string.Format("Screen Position:{0:d}, {1:d}",
            Cursor.Position.X, Cursor.Position.Y);

        if(lsp_flag)
        {
            lep = e.Location;
            g. DrawLine (GreenPen, lsp, lep);
            lsp = lep;
            g.Dispose();
            GreenPen.Dispose();
        } else
        {
            lsp = e.Location;
            g.DrawRectangle (GreenPen, lsp.X, lsp.Y, 0.1f, 0.1f);
            g.Dispose();
            GreenPen.Dispose();
            lsp_flag = true;
        }

        // Right-click to determine the end point
        if (e.Button==MouseButtons.Right)
        {
            lsp_flag=false;
        }
    }
}


2022-09-30 12:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.