c# - Bug when drawing rectangles in my Paint Program -
public partial class form1 : form { point downpoint , uppoint; list<shapes> shapes = new list<shapes>(); public shapesenum shapetype; public form1() { initializecomponent(); } protected override void onpaint(painteventargs e) { base.onpaint(e); foreach (var s in shapes) s.draw(e.graphics); } protected override void onmousedown(mouseeventargs e) { downpoint = e.location; } protected override void onmouseup(mouseeventargs e) { base.onmouseup(e); uppoint = e.location; createshape(); this.invalidate(); } private void createshape() { if (shapetype == shapesenum.circle) { rectangle rect = new rectangle(downpoint.x, downpoint.y, uppoint.x - downpoint.x, uppoint.y - downpoint.y); ellipse ellipse = new ellipse() { rect = rect }; shapes.add(ellipse); } else if (shapetype == shapesenum.rectangle) { rectangle rect = new rectangle(downpoint.x, downpoint.y, uppoint.x - downpoint.x, uppoint.y - downpoint.y); rect rectangle = new rect() { rect = rect }; shapes.add(rectangle); } else if (shapetype == shapesenum.line) { point pt1 = new point (uppoint.x, uppoint.y); point pt2 = new point (downpoint.x, downpoint.y); ln rectangle = new ln() { pointup = pt1, pointdown = pt2 }; shapes.add(rectangle); } lblstatus.text = string.format("dn:{0} up:{1} ct:{2}", downpoint, uppoint, shapes.count()); } private void btncircle_click(object sender, eventargs e) { shapetype = shapesenum.circle; } private void btnrectangle_click(object sender, eventargs e) { shapetype = shapesenum.rectangle; } private void btnline_click(object sender, eventargs e) { shapetype = shapesenum.line; } }
this main part of paint program.
public enum shapesenum { circle, rectangle, line } abstract class shapes { public rectangle rect { get; set; } public color color { get; set; } public bool isfilled { get; set; } public abstract void draw(graphics g); } class ellipse : shapes { public override void draw(graphics g) { g.drawellipse(pens.black, rect); } } class rect : shapes { public override void draw(graphics g) { g.drawrectangle(pens.black, rect); } } class ln : shapes { public point pointup { get; set; } public point pointdown { get; set; } public override void draw(graphics g) { g.drawline(pens.black, pointup, pointdown); } }
this class used inheritance on shapes. depending on shape, 1 of classes called.
drawing ovals works fine. same goes drawing lines. however, there bug when comes drawing rectangles. if put mouse , drag , let go left bottom right, work. however, if go direction invisible on form shapes.count()
still adds towards list of shapes
.
what caused bug?
try in order have start , end points right way:
int x0 = math.min(uppoint.x, downpoint.x); int y0 = math.min(uppoint.y, downpoint.y); point upperleft = new point(x0, y0); int x1 = math.max(uppoint.x, downpoint.x); int y1 = math.max(uppoint.y, downpoint.y); point lowerright = new point(x1, y1);
and
rectangle rect = new rectangle(x0, y0, x1 - x0, y1 - y0);
Comments
Post a Comment