C
C#2mo ago
CHΔNGΕ

drawing Rectangles in winforms c# help

Point shapestartP = new Point(0, 0);
private void picBoxMain_MouseUp(object sender, MouseEventArgs e)
{
flagDraw = false;
g = Graphics.FromImage(bm);



if (flagDrawingTool == "Rectangle")
{
g.DrawRectangle(pen, shapestartP.X, shapestartP.Y,Math.Abs(e.Location.X - shapestartP.X ),Math.Abs(e.Location.Y - shapestartP.Y));
}
g.Dispose();
picBoxMain.Invalidate();


}
private void picBoxMain_MouseDown(object sender, MouseEventArgs e)
{

shapestartP = e.Location;
}
Point shapestartP = new Point(0, 0);
private void picBoxMain_MouseUp(object sender, MouseEventArgs e)
{
flagDraw = false;
g = Graphics.FromImage(bm);



if (flagDrawingTool == "Rectangle")
{
g.DrawRectangle(pen, shapestartP.X, shapestartP.Y,Math.Abs(e.Location.X - shapestartP.X ),Math.Abs(e.Location.Y - shapestartP.Y));
}
g.Dispose();
picBoxMain.Invalidate();


}
private void picBoxMain_MouseDown(object sender, MouseEventArgs e)
{

shapestartP = e.Location;
}
This code is flawed as when u drag the cursor from bottom to up it stills draws the rectangle upwards. Any suggestions?
1 Reply
Anton
Anton2mo ago
you need two positions if you want the direction to affect how it draws ah actually no, you already have one, e.Location you just have to update the stored position so it's withing a circle of a radius of the size of the square around the cursor if it's already within, keep it as is if not, project it onto the circumference of the circle
a = prevPosition
b = e.Location
t = b - a
len = || t ||
if (len < size)
{
return b;
}
else
{
return t * (size / len);
}
a = prevPosition
b = e.Location
t = b - a
len = || t ||
if (len < size)
{
return b;
}
else
{
return t * (size / len);
}
if that's what you meab if you don't know what this is, learn linear algebra watch 3b1b's series on youtube ah no you mean something else for sure well that's just because you're doing the absolute value you need to make the smallest (x, y) the top left
void swapIfSmaller(ref float a, ref float b)
{
if (a > b)
{
return;
}
float t = a;
a = b;
b = t;
}

(x1, y1) = e.Location
(x2, y2) = prevPosition
swapIfSmaller(ref x1, ref x2);
swapIfSmaller(ref y1, ref y2);
return rect
{
topleft = (x2, y2),
size = (x1 - x2, y1 - y2),
};
void swapIfSmaller(ref float a, ref float b)
{
if (a > b)
{
return;
}
float t = a;
a = b;
b = t;
}

(x1, y1) = e.Location
(x2, y2) = prevPosition
swapIfSmaller(ref x1, ref x2);
swapIfSmaller(ref y1, ref y2);
return rect
{
topleft = (x2, y2),
size = (x1 - x2, y1 - y2),
};
Want results from more Discord servers?
Add your server