I need to be able to draw a polygon using mouse click locations.
Here is my current code:
//the drawshape varible is called when a button is pressed to select use of this tool
if (DrawShape == 4)
{
Point[] pp = new Point[3];
pp[0] = new Point(e.Location.X, e.Location.Y);
pp[1] = new Point(e.Location.X, e.Location.Y);
pp[2] = new Point(e.Location.X, e.Location.Y);
Graphics G = this.CreateGraphics();
G.DrawPolygon(Pens.Black, pp);
}
Thanks
Ok here is some sample code:
private List<Point> polygonPoints = new List<Point>();
private void TestForm_MouseClick(object sender, MouseEventArgs e)
{
switch(e.Button)
{
case MouseButtons.Left:
//draw line
polygonPoints.Add(new Point(e.X, e.Y));
if (polygonPoints.Count > 1)
{
//draw line
this.DrawLine(polygonPoints[polygonPoints.Count - 2], polygonPoints[polygonPoints.Count - 1]);
}
break;
case MouseButtons.Right:
//finish polygon
if (polygonPoints.Count > 2)
{
//draw last line
this.DrawLine(polygonPoints[polygonPoints.Count - 1], polygonPoints[0]);
polygonPoints.Clear();
}
break;
}
}
private void DrawLine(Point p1, Point p2)
{
Graphics G = this.CreateGraphics();
G.DrawLine(Pens.Black, p1, p2);
}
First, add this code:
List<Point> points = new List<Point>();
On the object you are drawing on, capture the OnClick event. One of the arguments should have the X and Y coordinates of the click. Add them to the points array:
points.Add(new Point(xPos, yPos));
And then finally, where you're drawing the lines, use this code:
if (DrawShape == 4)
{
Graphics G = this.CreateGraphics();
G.DrawPolygon(Pens.Black, points.ToArray());
}
EDIT:
Ok, so the above code isn't exactly correct. First of all, its most likely a Click event instead of a OnClick event. Second, To get the mouse position, you need two variables declared up with the points array,
int x = 0, y = 0;
Then have a mouse move event:
private void MouseMove(object sender, MouseEventArgs e)
{
x = e.X;
y = e.Y;
}
Then, in your Click event:
private void Click(object sender, EventArgs e)
{
points.Add(new Point(x, y));
}
Related
I have pictureBox click event. I get coordinates of click and try t draw circle:
private void pictureMain_Click(object sender, EventArgs e){
MouseEventArgs me = (MouseEventArgs)e;
Point coordinates = me.Location;
int x = coordinates.X;
int y = coordinates.Y;
// Create pen.
Pen blackPen = new Pen(Color.Red, 2);
// Create rectangle for ellipse.
Rectangle rect = new Rectangle(x, y, 50, 50);
g.DrawEllipse(blackPen, rect);
}
But it draws circle not in coordinates(x,y) of picturebox. It places circle in another place.
Try this:
private void pictureBox1_Click (object sender, EventArgs e)
{
Point ellipseCenter = ((MouseEventArgs) e).Location;
Size ellipseSize = new Size (50, 50);
Point rectPosition = new Point (ellipseCenter.X - ellipseSize.Width / 2, ellipseCenter.Y - ellipseSize.Height / 2);
Rectangle rect = new Rectangle (rectPosition, ellipseSize);
using (Graphics grp = Graphics.FromImage (pictureBox1.Image))
{
grp.DrawEllipse (Pens.Red, rect);
}
pictureBox1.Refresh ();
}
I already drew ellipse using
g.DrawEllipse(p, 0, 0, 100, 100);
p = new Pen(Color.Red, 1f);
This is my code for moving picturbox
int x, y;
private void timer1_Tick(object sender, EventArgs e)
{
y+=5;
x += 2;
pictureBox3.Location = new Point(x, y);
Invalidate();
}
Picture box move in correctly ...
But I want ...How can i move Picturebox inside that ellipse?
Ellipse should be fixed one..
I am using visual studio c# windows form, I need help to draw a circle using the Mouse click.. first click will give me the center of the circle equal to the cursor position and the second click will give me a point on the border of the circle equal to the second position of the cursor, the distance between the to points will give me the radius..now I have radius and point ..I can draw a circle ..The code doesn't work because I only can get one position of the cursor no matter how many times I click the mouse
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
int lastX = Cursor.Position.X;//the first click x cursor position
int lastY = Cursor.Position.Y;//the first click y cursor position,
//is there any way to reuse the Cursor.Position for different point ??
int x = Cursor.Position.X;//the second click x cursor position
int y = Cursor.Position.Y;//the second click y cursor position
Graphics g;
double oradius=Math.Sqrt(((lastX-x)^2) +((lastY-y)^2));
//double newy = Math.Sqrt(lastY);
// int newxv = Convert.ToInt32(newx);
int radius= Convert.ToInt32(oradius);
g = this.CreateGraphics();
Rectangle rectangle = new Rectangle();
PaintEventArgs arg = new PaintEventArgs(g, rectangle);
DrawCircle(arg, x, y,radius,radius);
}
private void DrawCircle(PaintEventArgs e, int x, int y, int width, int height)
{
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
e.Graphics.DrawEllipse(pen, x - width / 2, y - height / 2, width, height);
}
}
You need to store the first click as well before you start doing the calculations. One way to do this is to create a class that simply throws an event every second time you pass it x and y coordinates like this:
public class CircleDrawer
{
private int _firstX;
private int _firstY;
private int _secondX;
private int _secondY;
private bool _isSecondClick;
private event EventHandler OnSecondClick;
public void RegisterClick(int x, int y)
{
if(_isSecondClick)
{
_secondX = x;
_secondY = y;
if(OnSecondClick != null)
OnSecondClick(this, null);
}
else
{
_firstX = x;
_firstY = y;
_isSecondClick = true;
}
}
}
You can then in your code simply call your methods:
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
int lastX = Cursor.Position.X;//the first click x cursor position
int lastY = Cursor.Position.Y;//the first click y cursor position,
_circleDrawer.RegisterClick(lastX, lastY);
}
And in your constuctor:
public MyForm()
{
_circleDrawer = new CircleDrawer();
_circleDrawer.OnSecondClick += DrawCircle();
}
public void DrawCircle()
{
// Your drawing code
}
Your lastX and lastY are local variables, and you initialize them in the beginning of the MouseDown event handler. They should be class level variables and should be populated at the end of the MouseDown event handler.
Also, you should test if they already have a value, and only if they have value then draw the circle and then clear them (so that the next circle will have it's own center).
Here is an improvement of your code. Note I've used the using keyword with the graphics object and with the pen - get used to use it every time you are using an instance of anything that's implementing the IDisposable interface.
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (_lastPosition != Point.Empty)
{
var currentPosition = Cursor.Position;
var oradius = Math.Sqrt(((_lastPosition.X - currentPosition.X) ^ 2) + ((_lastPosition.Y - currentPosition.Y) ^ 2));
var radius = Convert.ToInt32(oradius);
using (var g = this.CreateGraphics())
{
var arg = new PaintEventArgs(g, new Rectangle());
DrawCircle(arg, currentPosition, radius, radius);
}
_lastPosition = Point.Empty;
}
else
{
_lastPosition = Cursor.Position;
}
}
private void DrawCircle(PaintEventArgs e, Point position, int width, int height)
{
using (var pen = new System.Drawing.Pen(System.Drawing.Color.Red, 3))
{
e.Graphics.DrawEllipse(pen, position.X - width / 2, position.Y - height / 2, width, height);
}
}
Note: This code can be improved even further.
There are many things fundamentally wrong with this code, here is a complete, working example.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Point clickCurrent = Point.Empty;
private Point clickPrev = Point.Empty;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
clickPrev = clickCurrent;
clickCurrent = this.PointToClient(Cursor.Position);
if (clickPrev == Point.Empty) return;
Graphics g;
double oradius = Math.Sqrt((Math.Pow(clickPrev.X - clickCurrent.X, 2)) + (Math.Pow(clickPrev.Y - clickCurrent.Y, 2)));
int radius = Convert.ToInt32(oradius);
g = this.CreateGraphics();
Rectangle rectangle = new Rectangle();
PaintEventArgs arg = new PaintEventArgs(g, rectangle);
DrawCircle(arg, clickPrev.X, clickPrev.Y, radius * 2, radius * 2);
clickCurrent = Point.Empty;
}
private void DrawCircle(PaintEventArgs e, int x, int y, int width, int height)
{
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
e.Graphics.DrawEllipse(pen, x - width / 2, y - height / 2, width, height);
}
}
private int _firstX;
private int _firstY;
private int _secondX;
private int _secondY;
private bool _isSecondClick;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (_isSecondClick)
{
_secondX = Cursor.Position.X;
_secondY = Cursor.Position.Y;
var radious1 = Math.Pow(_firstX - _secondX, 2);
var radious2 = Math.Pow(_firstY - _secondY, 2);
var radious = Math.Sqrt(radious1 + radious2);
Graphics g = this.CreateGraphics();
Rectangle rectangle = new Rectangle();
PaintEventArgs arg = new PaintEventArgs(g, rectangle);
DrawCircle(arg, _secondX, _secondY, radious, radious);
}
else
{
_firstX = Cursor.Position.X;
_firstY = Cursor.Position.Y;
_isSecondClick = true;
}
}
private void DrawCircle(PaintEventArgs arg, int x, int y, double width, double height)
{
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
var xL = Convert.ToInt32(x - width / 2);
var yL = Convert.ToInt32(y - height / 2);
var hL = Convert.ToInt32(height);
var wL = Convert.ToInt32(width);
arg.Graphics.DrawEllipse(pen, xL, yL, wL, hL);
}
i have PictureBox, how can I draw a shape/line that fires on MouseEnter event and change color or do more.
private void ImgViewer_Paint(object sender, PaintEventArgs e)
{
var graph = e.Graphics;
using (var pen = new Pen(Color.FromArgb(0, 255, 0)))
graph.DrawLine(pen, x1, y1, x2, y2);
}
this code is not enough, i guess
If you know the equation of the shape you could calculate whether the mouse is within or outside the shape area. Note that this is easy if the shape is consisted of the straight lines or circles (ellipses) for which the geometrical equations are relatively simple. For instance if your shape is a triangle with x and y coordinates (10,10), (50,10) and (30,50) than you should derive the equations of the lines using the equation of the line in two points:
y-y1 = ((y2-y1)/(x2-x1))*(x-x1)
the equations of the lines of our triangle would be:
y=1
y=2*x-10
y=-2*x+110
We should draw that triangle on some canvas, let's say on the PictureBox with FixedSingle border. Add the Paint event handler
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Point[] p = new Point[3];
p[0] = new Point(10,10);
p[1] = new Point(50,10);
p[2] = new Point(30,50);
e.Graphics.DrawLines(Pens.Black, p);
e.Graphics.FillPolygon(Brushes.Red, p);
}
We should add the MouseMove event handler for the PictureBox
bool inside = false;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Y > 10 && e.Y < 2 * e.X - 10 && e.Y < -2 * e.X + 110)
{
if (!inside)
{
inside = true;
HandleMouseEnter();
}
}
else
inside = false;
}
void HandleMouseEnter()
{
MessageBox.Show("Mouse inside");
}
In if statement whether the mouse cursor is within the triangle (note that the coordinate origin in C# is on the top-left corner but it is similar to the real geometry). The HandleMouseEnter is the method that handles the mouse enter.
You could use similar approach for an arbitrary shape but you should have geometry equations that describe it.
I want to move a Diamond Shape in the form(for example 2 pixels every 200ms) horizantally.
I used the following code in From_Paint Event.
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Point p1 = new Point(5,0);
Point p2 = new Point(10, 5);
Point p3 = new Point(5, 10);
Point p4 = new Point(0, 5);
Point[] ps = { p1, p2, p3, p4, p1 };
g.DrawLines(Pens.Black, ps);
}
I know how to move a picturebox but how to do with shape.
Thanks,
Ani
You'll need to track your current location in a form level variable. If you do this, your Form1_Paint event can change the X pixel location each time it draws.
Just add a Timer to your form, and set it's interval to 200ms. Each 200ms, add 2 to your current X pixel, and invalidate your control (so it redraws).
Edit: Add this to your form:
int xOffset = 0;
Then, in your timer_Tick:
private void timer1_Tick(object sender, EventArgs e)
{
if (xOffset < 500)
xOffset += 2;
else
timer1.Enabled = false; // This will make it only move 500 pixels before stopping.... Change as desired.
this.Invalidate(); // Forces repaint
}
Change your paint event to:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Point p1 = new Point(5 + xOffset,0);
Point p2 = new Point(10 + xOffset, 5);
Point p3 = new Point(5 + xOffset, 10);
Point p4 = new Point(0 + xOffset, 5);
Point[] ps = { p1, p2, p3, p4, p1 };
g.DrawLines(Pens.Black, ps);
}
use Timer then redraw on each tick.