'Drawing shapes into the Rectangle
I developing paint application with winform and i have to draw some custom shapes(right arrow, left arrow, trapezoid, rhombus etc) but i dont understand how drawPolygon method drawing wrong coordinates. I have a ShapeFactory class and i create shape by geometricalShape enum. I just add coordinates of shape into the class but it doesnt draw correctly.
GeometricalShape Enum:
public enum GeometricalShape
{
Left_Arrow,
Right_Arrow,
Triangle,
Left_Triangle,
Right_Triangle,
Bottom_Triangle,
Rounded_Rectangle,
Diamond,
Pentagon,
Hexagon,
Star,
Six_Pointed_Star,
Parallelogram,
Trapezoid,
Rectangle,
Circle,
Cube,
}
ShapeFactory Class:
public static class ShapeFactory
{
private static IShape desiredShape;
public static IShape GetShapeBase(GeometricalShape shape)
{
switch (shape)
{
.
.
case GeometricalShape.Triangle:
desiredShape = new Triangle();
break;
.
.
}
return desiredShape;
}
}
All shapes uses IShape interface. Some regular shapes uses RegularShapeBase abstract class also.
public interface IShape
{
public void Draw(Graphics graphics, System.Drawing.Rectangle rect, Pen pen);
public void Fill(Graphics graphics, System.Drawing.Rectangle rect, Brush brush);
}
public abstract class RegularShapeBase: IShape
{
public abstract Point[] GetCoordinates(System.Drawing.Rectangle rect);
public void Draw(Graphics graphics, System.Drawing.Rectangle rect, Pen pen)
{
graphics.DrawPolygon(pen, GetCoordinates(rect));
}
public void Fill(Graphics graphics, System.Drawing.Rectangle rect, Brush brush)
{
graphics.FillPolygon(brush, GetCoordinates(rect));
}
}
Then, triangle class with its own coordinates:
public class Triangle : RegularShapeBase
{
public override Point[] GetCoordinates(System.Drawing.Rectangle rect)
{
return new Point[]
{
new Point(rect.X,rect.Height), //Left bottom
new Point(Math.Abs(rect.Width / 2),rect.Y),//Top center
new Point(rect.Width,rect.Height),//Right bottom
};
}
}
Expected Drawing and Actual Drawing
I expected that codes must be work successfully but it didnt work unfortunately. I think the problem is X and Y coordinates of current shape (Triangle in this problem) aren't inside rectangle. That X and Y coordinates started from left of picturebox instead of left of Rectangle. That is the main problem. How can i solve this problem and create general answer? Because i have many classes related custom shapes like Rounded Rectangle, Hexagon etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
