参照TaW提供的WinForms绘图代码,如何在DrawAction类中声明矩形外的形状?
嘿,针对你遇到的这个问题,我来给你一步步拆解解决方案!.NET WinForms的基础类库确实只内置了Rectangle(以及浮点版的RectangleF)这类基础形状结构体,没有现成的Triangle、Hexagon类型——不过没关系,我们可以自己定义数据结构来存储这些形状的关键信息,或者用现有类型封装,下面分每个形状给你具体操作方案:
椭圆的绘制本质上依赖一个边界矩形(椭圆刚好被这个矩形框住,四条边和椭圆相切),所以完全可以用现有类型来存储:
在你的DrawAction类里直接声明:
// 用整数坐标的Rectangle,适合像素对齐的场景 public Rectangle EllipseBounds { get; set; } // 或者用浮点版的RectangleF,适合需要更精确位置的场景 public RectangleF EllipseBounds { get; set; }
后续绘图时,调用Graphics.DrawEllipse()方法,传入这个矩形就能画出对应的椭圆啦。
三角形需要三个顶点的坐标来确定,有两种常见处理方式:
方案一:自定义Triangle结构体
如果想让代码更语义化,自己定义一个结构体专门存三角形的三个顶点:
public struct Triangle { public Point Point1 { get; set; } public Point Point2 { get; set; } public Point Point3 { get; set; } public Triangle(Point p1, Point p2, Point p3) { Point1 = p1; Point2 = p2; Point3 = p3; } }
然后在DrawAction类里声明:
public Triangle CurrentTriangle { get; set; }
方案二:用Point数组存储
如果不想额外定义结构体,直接用数组也很方便:
public Point[] TrianglePoints { get; set; } // 注意初始化的时候要确保数组长度是3哦
绘图时调用Graphics.DrawPolygon()或者Graphics.FillPolygon()方法,传入这个点数组就能画出三角形了。
六边形需要六个顶点,处理思路和三角形一致:
方案一:自定义Hexagon结构体
同样可以定义语义化的结构体:
public struct Hexagon { public Point Point1 { get; set; } public Point Point2 { get; set; } public Point Point3 { get; set; } public Point Point4 { get; set; } public Point Point5 { get; set; } public Point Point6 { get; set; } public Hexagon(Point p1, Point p2, Point p3, Point p4, Point p5, Point p6) { Point1 = p1; Point2 = p2; Point3 = p3; Point4 = p4; Point5 = p5; Point6 = p6; } }
然后在DrawAction类中声明:
public Hexagon CurrentHexagon { get; set; }
方案二:用Point数组存储
直接用数组简化代码:
public Point[] HexagonPoints { get; set; } // 初始化时记得保证数组长度是6
绘图时同样用Graphics.DrawPolygon()或Graphics.FillPolygon()方法即可。
如果你的DrawAction类需要支持切换不同形状绘制,不妨加一个枚举来标记当前要画的形状类型,再配合对应的属性,这样代码逻辑会更清晰:
public enum ShapeType { Rectangle, Ellipse, Triangle, Hexagon } public class DrawAction { public ShapeType CurrentShape { get; set; } public Rectangle CurrentRectangle { get; set; } public RectangleF EllipseBounds { get; set; } public Point[] TrianglePoints { get; set; } public Point[] HexagonPoints { get; set; } // 还可以加一些通用属性,比如线条颜色、宽度、是否填充等 }
这样在绘图逻辑里,就能根据CurrentShape的值来选择对应的属性和绘图方法,代码维护起来会轻松很多~
内容的提问来源于stack exchange,提问作者PreS

