How can I resize a rectangle with Mouse_down
and Mouse_move
event in C# ?
I drew 2 rectangles and I want to resize them with the corners. (The left top corner is because of the moving.) The blue rectangle have to contain the red one.
That's my code:
namespace __RajzAlap
{
public partial class Form1 : Form
{
Graphics g;
Pen bluePen = new Pen(Color.Blue, 2);
Pen redPen = new Pen(Color.Red, 2);
PointF balfont = new PointF(100, 100);
PointF balfont2 = new PointF(120, 120);
int meret1 = 300;
int meret2 = 30;
int megfogva = -1;
float s = 5;
public Form1()
{
InitializeComponent();
}
private void canvas_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
Rectangle kekTeglalap = new Rectangle((int)balfont.X, (int)balfont.Y, meret1, meret1);
Rectangle pirosTeglalap = new Rectangle((int)balfont2.X, (int)balfont2.Y, meret2, meret2);
g.DrawRectangle(bluePen, kekTeglalap);
g.DrawRectangle(redPen, pirosTeglalap);
//sarkok rajzolása
g.FillRectangle(new SolidBrush(Color.Blue), balfont.X - s, balfont.Y - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Blue), balfont.X + meret1 - s, balfont.Y + meret1 - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Blue), balfont.X + meret1 - s, balfont.Y - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Blue), balfont.X - s, balfont.Y + meret1 - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Red), balfont2.X - s, balfont2.Y - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Red), balfont2.X + meret2 - s, balfont2.Y - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Red), balfont2.X - s, balfont2.Y + meret2 - s, 2 * s, 2 * s);
g.FillRectangle(new SolidBrush(Color.Red), balfont2.X + meret2 - s, balfont2.Y + meret2 - s, 2 * s, 2 * s);
}
#region Mouse handling
private void canvas_MouseDown(object sender, MouseEventArgs e)
{
//bal felső sarok mozgatás
if (Megfogva(balfont, e.Location, s)) megfogva = 0;
else if (Megfogva(balfont2, e.Location, s)) megfogva = 1;
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
//bal felső sarok mozgatás
if (megfogva != -1)
{
switch (megfogva)
{
case 0: balfont = e.Location; break;
case 1: balfont2 = e.Location; break;
default: break;
}
canvas.Refresh();
}
}
private void canvas_MouseUp(object sender, MouseEventArgs e)
{
megfogva = -1;
}
private void canvas_MouseWheel(object sender, MouseEventArgs e)
{
}
#endregion
//bal felső sarok mozgatáa
private bool Megfogva(PointF p, PointF eger, float tavolsag)
{
return Math.Abs(p.X - eger.X) <= tavolsag &&
Math.Abs(p.Y - eger.Y) <= tavolsag;
}
}
}