Getting user input for parameters then draw shape C# - c#

Pic of Form
I am trying to get input from the user to set the x, y coordinates to the DrawEllipse function, when i hard code the values into it it draws a circle on the screen just fine however when i try passing in a int that has come from user input it doesn't work.
I am trying to make a program that responds to commands from users e.g. the user can type in "draw shape x y".
The string is being split when a space is detected the string is split into an array.
public partial class Form1 : Form
{
String input;
Bitmap drawOutput;
String command, command2, command3;
int x, y;
public Form1()
{
InitializeComponent();
drawOutput = new Bitmap(OutputBox.Size.Width, OutputBox.Size.Height);
OutputBox.Image = drawOutput;
}
private void Form1_Load(object sender, EventArgs e)
{
Graphics g;
g = Graphics.FromImage(drawOutput);
Pen mypen = new Pen(Color.Black);
g.Clear(Color.White);
g.Dispose();
}
private void CMDBox_TextChanged(object sender, EventArgs e)
{
input = CMDBox.Text;
}
private void ExecuteBtn_Click(object sender, EventArgs e)
{
String[] spilt = input.Split(' ');
foreach (String words in spilt)
{
command = spilt[0];
command2 = spilt[1];
command3 = spilt[2];
x = Int32.Parse(command2);
y = Int32.Parse(command3);
Graphics g;
g = Graphics.FromImage(drawOutput);
Pen pen = new Pen(Color.Black, 5);
if (input == command)
{
g.DrawEllipse(pen, 0, 0, x, y);
OutputBox.Image = drawOutput;
g.Dispose();
}
}
}
}
Can anyone help?

Related

this.Refresh() blocks new graphs

I was working a program where a rectangle is drawn inside a label through a paint event. Then with a button click event I want to redraw the inside of label now having the original rectangle and a new one that is .TranslateTransform some some input. Now to the problem: I was able to create the new original and the copy but if I press the button then I get a copy of the copy. I thought I could fix this if before the redrawing I use label.Refresh() or .Invalidate() but now I can't even get a single copy.
Thanks in advance for the help. Here is the code:
public int x, y;
public float p, q;
Graphics g;
SolidBrush brush1 = new SolidBrush(Color.Green);
public Form1()
{
InitializeComponent();
}
private void label5_Paint_1(object sender, PaintEventArgs e)
{
g = e.Graphics;
g.FillRectangle(brush1, 50, 50, 100, 50);
}
private void shift(object sender, PaintEventArgs e)
{
string a, b;
a = textBox1.Text;
x = int.Parse(a);
b = textBox2.Text;
y = int.Parse(b);
var g = e.Graphics;
Brush br = new SolidBrush(Color.DarkOrange);
g.TranslateTransform(x, y);
g.FillRectangle(br, 50, 50, 100, 50);
}
private void button1_Click(object sender, EventArgs e)
{
label5.Invalidate();
label5.Paint += new PaintEventHandler(shift);
}
private void resize(object sender, PaintEventArgs e)
{
string c, d;
c = textBox3.Text;
p = float.Parse(c);
d = textBox4.Text;
q = float.Parse(d);
var g = e.Graphics;
Brush br = new SolidBrush(Color.DarkOrange);
g.ScaleTransform(p, q);
g.FillRectangle(br, 50, 50, 100, 50);
}
private void button2_Click(object sender, EventArgs e)
{
label5.Invalidate();
label5.Paint += new PaintEventHandler(resize);
}

How to take input from text to draw shapes on screen?

Hi all I am trying to create a program that takes commands from the user to draw shapes on the screen. The program should have basic commands to draw shapes and a clear command to clear the screen afterwards, the user should be able to type moveTo in the text box and the pen should move the the coordinates they set it to then the user should be able to type in the shape they want to draw(circle(radius), rectangle(width, height), triangle(side, side, side). I have got it to work for the rectangle as i want however struggling to implement the other parts can anyone help.
public partial class Form1 : Form
{
String input;
Bitmap drawOutput;
String command, command2, command3;
int x, y;
public Form1()
{
InitializeComponent();
drawOutput = new Bitmap(OutputBox.Size.Width, OutputBox.Size.Height);
OutputBox.Image = drawOutput;
}
private void Form1_Load(object sender, EventArgs e)
{
Graphics g;
g = Graphics.FromImage(drawOutput);
Pen mypen = new Pen(Color.Black);
g.Clear(Color.White);
g.Dispose();
}
private void CMDBox_TextChanged(object sender, EventArgs e)
{
input = CMDBox.Text;
}
private void ExecuteBtn_Click(object sender, EventArgs e)
{
string[] spilt = input.Split(' ');
foreach (String words in spilt)
{
command = spilt[0];
command2 = spilt[1];
command3 = spilt[2];
x = Int32.Parse(command2);
y = Int32.Parse(command3);
Graphics g;
g = Graphics.FromImage(drawOutput);
Pen pen = new Pen(Color.Black, 5);
if (command == "circle")
{
g.DrawEllipse(pen, 0, 0, x, y);
setImage(g);
}
else if (command == "rectangle")
{
g.DrawRectangle(pen, 0, 0, x, y);
setImage(g);
}
}
}
public void setImage(Graphics g)
{
g = Graphics.FromImage(drawOutput);
OutputBox.Image = drawOutput;
g.Dispose();
}
}
The basic context of this program is to create a really basic programming language which takes the users input and display it on screen
You don't need to declare a class level Bitmap (drawOutput) nor create Graphics object from it. You need to do the drawing in the Paint event handler. Try the following:
Declare enumeration for your shapes, class level variables to hold the type of the shape, x and y coordinates, and the size of the shape w and h.
enum Shapes
{
Ellipse,
Rectangle,
Line
}
int x, y, w, h;
Shapes shape;
Validate the user's input in the ExecuteBtn click event, assign the values, and call the OutputBox.Invalidate() if the input is correct.
var cmd = textBox1.Text.Split(' ');
var validCmds = Enum.GetNames(typeof(Shapes));
if (cmd.Length < 5 || !validCmds.Contains(cmd[0], StringComparer.OrdinalIgnoreCase))
{
MessageBox.Show("Enter a valid command.");
return;
}
if(!int.TryParse(cmd[1], out x) ||
!int.TryParse(cmd[2], out y) ||
!int.TryParse(cmd[3], out w) ||
!int.TryParse(cmd[4], out h))
{
MessageBox.Show("Enter a valid shape");
return;
}
shape = (Shapes)validCmds.ToList().FindIndex(a => a.Equals(cmd[0], StringComparison.OrdinalIgnoreCase));
OutputBox.Invalidate();
Draw the shape in the Paint event.
private void OutputBox_Paint(object sender, PaintEventArgs e)
{
if (w > 0 && h > 0)
{
e.Graphics.Clear(Color.White);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
using (Pen pn = new Pen(Color.Black, 5))
{
switch (shape)
{
case Shapes.Ellipse:
e.Graphics.DrawEllipse(pn, x, y, w, h);
break;
case Shapes.Rectangle:
e.Graphics.DrawRectangle(pn, x, y, w, h);
break;
case Shapes.Line:
e.Graphics.DrawLine(pn, x, y, w, h);
break;
}
}
}
}
Better yet, the Shape class approach as commented below.
Create the Shape class to enumerate your shapes, declare properties for them, and a method to parse a given command string and outs the required shape on success:
public class Shape
{
#region enums.
public enum Shapes
{
Ellipse,
Rectangle,
Line
}
#endregion
#region Constructors
public Shape()
{ }
public Shape(Shapes shape, int x, int y, int width, int height)
{
ThisShape = shape;
X = x;
Y = y;
Width = width;
Height = height;
}
#endregion
#region Properties
public Shapes ThisShape { get; set; } = Shapes.Ellipse;
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
#endregion
#region Methods
public static bool TryParse(string input, out Shape result)
{
result = null;
if (string.IsNullOrEmpty(input))
return false;
var cmd = input.Split(' ');
var validCmds = Enum.GetNames(typeof(Shapes));
if (cmd.Length < 5 || !validCmds.Contains(cmd[0], StringComparer.OrdinalIgnoreCase))
return false;
int x, y, w, h;
if (!int.TryParse(cmd[1], out x) ||
!int.TryParse(cmd[2], out y) ||
!int.TryParse(cmd[3], out w) ||
!int.TryParse(cmd[4], out h))
return false;
if (w <= 0 || h <= 0)
return false;
var shape = (Shapes)validCmds.ToList().FindIndex(a => a.Equals(cmd[0], StringComparison.OrdinalIgnoreCase));
result = new Shape(shape, x, y, w, h);
return true;
}
#endregion
}
In your Form, declare a shape variable:
Shape shape;
The ExecuteBtn click event:
shape = null;
if (!Shape.TryParse(textBox1.Text, out shape))
{
MessageBox.Show("Enter a valid command.");
return;
}
OutputBox.Invalidate();
Finally, your paint event:
private void OutputBox_Paint(object sender, PaintEventArgs e)
{
if (shape != null)
{
e.Graphics.Clear(Color.White);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
using (Pen pn = new Pen(Color.Black, 5))
{
switch (shape.ThisShape)
{
case Shape.Shapes.Ellipse:
e.Graphics.DrawEllipse(pn, shape.X, shape.Y, shape.Width, shape.Height);
break;
case Shape.Shapes.Rectangle:
e.Graphics.DrawRectangle(pn, shape.X, shape.Y, shape.Width, shape.Height);
break;
case Shape.Shapes.Line:
//Note: the Width and Height properties play here the X2 and Y2 roles.
e.Graphics.DrawLine(pn, shape.X, shape.Y, shape.Width, shape.Height);
break;
}
}
}
}

Resize rectangle with form Size in real time?

Here is the following rectangle below:
When I resize the form, I need this rectangle to match the size of the form.
When changing the width of the rectangle, do not interfere with its visibility within the form.
I'm using the following:
Note:
I did the rectangle manually, but if you have rectangle ready, better yet!
public Form1()
{
InitializeComponent();
this.Paint += Form1_Paint;
this.rectangles = new Dictionary<string, Rectangle>();
this.sizeScreen = this.Size;
this.sizeRectangles = new Size(8, 8);
this.brush = new SolidBrush(Color.Red);
FillLeft();
FillRight();
FillUp();
FillDown();
}
private Size sizeScreen;
private Size sizeRectangles;
private SolidBrush brush;
private Dictionary<string, Rectangle> rectangles;
private void FillLeft()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("left", rectangle);
}
private void FillRight()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = this.sizeScreen.Width - (this.sizeRectangles.Width * 5),
Y = this.sizeRectangles.Height
};
this.rectangles.Add("right", rectangle);
}
private void FillUp()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("up", rectangle);
}
private void FillDown()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeScreen.Height - (this.sizeRectangles.Height * 11)
};
this.rectangles.Add("down", rectangle);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < this.rectangles.Count; i++)
{
e.Graphics.FillRectangles(this.brush, this.rectangles.Values.ToArray());
}
}
I want to set the rectangle on the form when it is resized
This is the way I'm creating the rectangle, but it does not stay right on the screen, to resize it I do not know
I think this would simplify what you are trying to do:
const int PenWidth = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
You could even add a margin:
const int PenWidth = 10;
const int PenMargin = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
r.Inflate(-PenMargin, -PenMargin);
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
To prevent traces (suggested by Wyck):
private void Form1_Resize(object sender, EventArgs e)
{
Invalidate();
}
Handle the Resize event and call Invalidate in the handler. Create a Pen of the desired color and width and set its Alignment to Inset. Handle the Paint event and in the handler call DrawRectangle passing in the ClientRectangle of the form.
Here is an example.
const float borderWidth = 8.0f;
Pen borderPen = new Pen(Color.Red, borderWidth) { Alignment = System.Drawing.Drawing2D.PenAlignment.Inset };
public Form2()
{
InitializeComponent();
this.Paint += Form2_Paint;
this.Resize += Form2_Resize;
}
private void Form2_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(borderPen, this.ClientRectangle);
}
Apply the following fixes to the code:
Set ResizeRedraw property of the form to true. It sets the underlying style for the form so by each resize it sends the paint message and you don't need to handle Resize event.
Use DrawRectangle and draw using wide pen. So you don't need to fill multiple rectangles.
Set the PenAlignment to Inset. So you don't need to calculate the location of rectangle.
Do dispose the pen when you don't need it.
Example
public Form1()
{
InitializeComponent();
ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var pen = new Pen(Color.Red, PenWidth))
{
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
e.Graphics.DrawRectangle(pen, ClientRectangle);
}
}
i have used this on my current project. when ever you resize the form, it will automatically resize all the object inside your form
i have class named clsResize and i call this on the form load.
1st you have to initialize the class inside the form then create 2 new method.
see example below
public partial class frmNewForm : Form
{
clsResize _form_resize;
public string selectedProd;
public frmNewForm()
{
InitializeComponent();
_form_resize = new clsResize(this);
this.Load += _Load;
this.Resize += _Resize;
}
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
private void _Resize(object sender, EventArgs e)
{
_form_resize._resize();
}
}
and here is the class that i used.
public class clsResize
{
List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
private bool showRowHeader = false;
public clsResize(Form _form_)
{
form = _form_; //the calling form
_formSize = _form_.ClientSize; //Save initial form size
_fontsize = _form_.Font.Size; //Font size
}
private float _fontsize { get; set; }
private System.Drawing.SizeF _formSize {get;set; }
private Form form { get; set; }
public void _get_initial_size() //get initial size//
{
var _controls = _get_all_controls(form);//call the enumerator
foreach (Control control in _controls) //Loop through the controls
{
_arr_control_storage.Add(control.Bounds); //saves control bounds/dimension
//If you have datagridview
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
}
}
public void _resize() //Set the resize
{
double _form_ratio_width = (double)form.ClientSize.Width /(double)_formSize.Width; //ratio could be greater or less than 1
double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height; // this one too
var _controls = _get_all_controls(form); //reenumerate the control collection
int _pos = -1;//do not change this value unless you know what you are doing
try
{
foreach (Control control in _controls)
{
// do some math calc
_pos += 1;//increment by 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height)); //use for sizing
System.Drawing.Point _controlposition = new System.Drawing.Point((int)
(_arr_control_storage[_pos].X * _form_ratio_width), (int)(_arr_control_storage[_pos].Y * _form_ratio_height));//use for location
//set bounds
control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize); //Put together
//Assuming you have a datagridview inside a form()
//if you want to show the row header, replace the false statement of
//showRowHeader on top/public declaration to true;
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
//Font AutoSize
control.Font = new System.Drawing.Font(form.Font.FontFamily,
(float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return;
}
}
private void _dgv_Column_Adjust(DataGridView dgv, bool _showRowHeader) //if you have Datagridview
//and want to resize the column base on its dimension.
{
int intRowHeader = 0;
const int Hscrollbarwidth = 5;
if (_showRowHeader)
intRowHeader = dgv.RowHeadersWidth;
else
dgv.RowHeadersVisible = false;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Dock == DockStyle.Fill) //in case the datagridview is docked
dgv.Columns[i].Width = ((dgv.Width - intRowHeader) / dgv.ColumnCount);
else
dgv.Columns[i].Width = ((dgv.Width - intRowHeader - Hscrollbarwidth) / dgv.ColumnCount);
}
}
private static IEnumerable<Control> _get_all_controls(Control c)
{
return c.Controls.Cast<Control>().SelectMany(item =>
_get_all_controls(item)).Concat(c.Controls.Cast<Control>()).Where(control =>
control.Name != string.Empty);
}
}

How to draw using trackbar?

well how do you draw in C# using variables?
ive managed to draw some shapes but only when i hardcode in the lengths. i need to draw shapes using a trackbar to get the lengths.
public abstract class Shape
{
//private String shape;
private int length;
}
public virtual void setLength(int newLength)
{
this.length = newLength;
}
public virtual int getLength()
{
return length;
}
//public String getShape()
//{
// return shape;
//}
//abstract public double getLength(float length);
abstract public float getPerimeter(int length);
abstract public float getArea(int length);
only showing square class but this project also includes triangle and square.
using System;
using System.Drawing;
public class Square : Shape
{
private float perimeter, area;
public override float getPerimeter(int length)
{
perimeter = length*4;
return perimeter;
}
public override float getArea(int length)
{
area = length*length;
return area;
}
}
this is the class with all my event handlers
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace shapes
{
//private System.Windows.Forms.TrackBar trackBar1;
public partial class Form1 : Form
{
private Shape shape;
private int length = 0;
private int shapeL = 0;
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
label3.Text = "Length Slider: " + trackBar1.Value;
textBox1.Text = shape.getPerimeter(shape.getLength()).ToString("0.00");
textBox2.Text = shape.getArea(shape.getLength()).ToString("0.00");
textBox1.Refresh();
textBox2.Refresh();
length = trackBar1.Value;
shape.setLength(length);
}
private void onCircleClick(object sender, EventArgs e)
{
shape = new Circle();
//length = trackBar1.Value;
length = shape.getLength();
this.Refresh();
using (Graphics g = this.panel1.CreateGraphics())
{
Pen pen = new Pen(Color.Black, 2);
Graphics formGraphics;
formGraphics = this.panel1.CreateGraphics();
formGraphics.DrawEllipse(pen, 50, 50, length, length);
//g.DrawEllipse(pen, 100, 100, length, length);
}
}
private void onSquareClick(object sender, EventArgs e)
{
shape = new Square();
length = trackBar1.Value;
using (Graphics g = this.panel1.CreateGraphics())
{
Pen pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, 50, 50, length, length);
System.Windows.Forms.MessageBox.Show("lenght is: " + length);
}
}
private void onTriangleClick(object sender, EventArgs e)
{
shape = new Triangle();
length = trackBar1.Value;
using (Graphics g = this.panel1.CreateGraphics())
{
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create points that define polygon.
Point point1 = new Point(50, 50);
Point point2 = new Point(50, 100);
Point point3 = new Point(100, 50);
Point[] curvePoints = { point1, point2, point3};
// Draw polygon to screen.
g.FillPolygon(blueBrush, curvePoints);
}
}
private void shapeToolStripMenuItem_Click(object sender, EventArgs e)
{
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Pen pen = new Pen(Color.Black, 2);
Graphics g = pe.Graphics;
g = this.CreateGraphics();
g.DrawRectangle(pen, 50, 50, length, length);
}
private void OnPaint(object sender, PaintEventArgs e)
{
}
}
}
yes its very messy, as you can see ive tried various things.
whats the difference between the panel1_paint and onPaint?
as you can see im not too sure how to use eventhandlers, the onCircleClick is basically a menu item button but how do i activate a different eveenthandler(panel1_Paint) from another eventhandler(onCircleClick)?
do graphics need to drawn in a *_paint/OnPaint method? ive gotten mine to draw in just the normal panel.
next is whats the best course of action to get the trackbar value to the shape object and back again to the method? yes the data is being saved (i think) when i use displayMessage(shape.getLength) it displays the length and is usually one off.
whats the equilent to repaint() in java for c#? ive tried this.Refresh(); but it doesnt work itll draw the shape then makes it disappear.
am i writing my setters/getters properly? or should i use
public int X
{
get {return x;}
set {x = value;}
}
in java, graphics will draw on any panel, in c# does it need to be in a specific container?
this is very simple, lets say that you want to draw on panel2.
all you have to do is to write this inside your private void panel2_Paint(object sender, PaintEventArgs e) body.
{
e.Graphics.Clear(panel1.BackgroundColor);
int length = trackBar1.Value;
Pen pen = new Pen(Color.Black, 2);
e.Graphics.DrawRectangle(pen, 50, 50, length, length);
}
and whenever you want to refresh the drawing, you can call either panel2.Refresh() or panel2.Invalidate(). both would do the job.
note that if you did this, panel2 won't get cleared after drawing the shape as it happened with you before.
note also that the panel would flicker as you change the trackbar value. i know how to handle this, but i don't want to complicate the solution for now.

Draw a line on PictureBox from parent

I have a PictureBox as UserControl. I added this User Control on the main form. Now I have to press a button and create a line on the user control. On my project, every time I press this button, I want to send to user control parameters of two PointF(x and y) and draw a new line, in addition to the existent one. I have so far the Paint event when picturebox is loaded.
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Pen graphPen = new Pen(Color.Red, 2);
PointF pt1D = new PointF();
PointF pt2D = new PointF();
pt1D.X = 0;
pt1D.Y = 10;
pt2D.X = 10;
pt2D.Y = 10;
e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}
Assuming that you want to draw the line on the click of the button, here's a modified version of your code:
List<PointF> points = new List<PointF>();
Pen graphPen = new Pen(Color.Red, 2);
private void btnDrawLines_Click(object sender, EventArgs e)
{
Graphics g = picBox.CreateGraphics();
PointF pt1D = new PointF();
PointF pt2D = new PointF();
pt1D.X = 0;
pt1D.Y = 10;
pt2D.X = 10;
pt2D.Y = 10;
g.DrawLine(graphPen, pt1D, pt2D);
points.Add(pt1D);
points.Add(pt2D);
}
private void picBox_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < points.Count; i+=2)
e.Graphics.DrawLine(graphPen, points[i], points[i + 1]);
}
Note that you can get a Graphics object through the PictureBox class's CreateGraphics() method which is the same as the e.Graphics object in the Paint event handler.
If you are adding lines to be drawn, the you probably want a little Line class:
public class Line {
public Point Point1 { get; set; }
public Point Point2 { get; set; }
public Line(Point point1, Point point2) {
this.Point1 = point1;
this.Point2 = point2;
}
}
And then you can just add these "lines" to a list:
private List<Line> _Lines = new List<Line>();
and add to them and tell the control to update it's drawing:
_Lines.Add(new Line(new Point(10, 10), new Point(42, 42)));
_Lines.Add(new Line(new Point(20, 40), new Point(20, 60)));
pictureBox1.Invalidate()
then in your drawing:
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.Clear(Color.White);
foreach (Line l in _Lines) {
e.Graphics.DrawLine(Pens.Red, l.Point1, l.Point2);
}
}

Categories

Resources