Come disegnare un rettangolo in C # utilizzando un mouse
-
01-10-2019 - |
Domanda
Voglio disegnare un rettangolo in un form in C #. Ho letto e ho trovato questo articolo . Ci sono dei campioni o tutorial disponibili? L'articolo non è stato molto utile.
Soluzione
L'articolo che appare legata ad essere C ++, che può spiegare il motivo per cui non ha aiutato molto.
Se si creano eventi per MouseDown e MouseUp, si dovrebbe avere i due punti angolari necessari per un rettangolo. Da lì, è una questione di disegno sul modulo. System.Drawing. * Dovrebbe probabilmente essere la vostra prima fermata. Ci sono un paio di tutorial link sottostante:
Disegno con grafica in WinForms utilizzando C #
disegnare un rettangolo utilizzando WinForms (StackOverflow)
Altri suggerimenti
È necessario questo 3 funzioni e variabili:
private Graphics g;
Pen pen = new System.Drawing.Pen(Color.Blue, 2F);
private Rectangle rectangle;
private int posX, posY, width, height;
In secondo luogo è necessario fare un mouse evento:
private void pictureCrop_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
posX = e.X;
posY = e.Y;
}
}
In terzo luogo, è necessario implemente il mouse su evento:
private void pictureCrop_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (e.X > posX && e.Y > posY) // top left to bottom right
{
width = Math.Abs(e.X - posX);
height = Math.Abs(e.Y - posY);
}
else if (e.X < posX && e.Y < posY) // bottom right to top left
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posX = e.X;
posY = e.Y;
}
else if (e.X < posX && e.Y > posY) // top right to bottom left
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posX = e.X;
}
else if (e.X > posX && e.Y < posY) // bottom left to top right
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posY = e.Y;
}
g.DrawImage(_bitmap, 0, 0);
rectangle = new Rectangle(posX, posY, width, height);
g = pictureCrop.CreateGraphics();
g.DrawRectangle(pen, rectangle);
}
E per garantire che quando si ridimensiona o si sposta il modulo il rettangolo sarà lì:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graph = e.Graphics;
graph.DrawImage(_bitmap, 0, 0);
Rectangle rec = new Rectangle(posX, posY, width, height);
graph.DrawRectangle(pen, rec);
}