这边通过接口来实现,使用的时候继承这个接口即可使用
csharp
public interface IShapeDraw
{
void DrawPolygon(DrawingContext dc, Brush brush, Pen? p, List<Point> points)
{
if (!points.Any())
return;
// 创建一个路径,并添加三角形的点
var geometry = new StreamGeometry();
using (var geometryContext = geometry.Open())
{
geometryContext.BeginFigure(points[0], true, true);
for (var i = 1; i < points.Count; i++)
{
geometryContext.LineTo(points[i], true, false);
}
}
// 绘制三角形并填充颜色
dc.DrawGeometry(brush, p, geometry);
}
/// <summary>
/// 三角形
/// </summary>
void DrawTriangle(DrawingContext dc, Brush brush, Pen? p, Point point1, Point point2, Point point3)
{
DrawPolygon(dc, brush, p, new List<Point>() { point1, point2, point3 });
}
/// <summary>
/// 棱形
/// </summary>
void DrawDiamond(DrawingContext dc, Brush brush, Pen? p, Point point1, Point point2, Point point3, Point point4)
{
DrawPolygon(dc, brush, p, new List<Point>() { point1, point2, point3, point4 });
}
/// <summary>
/// 十字型图
/// </summary>
void DrawCross(DrawingContext dc, Brush brush, Pen? p, List<Point> horizontal2Point, List<Point> vertical2Point)
{
if (horizontal2Point.Count != 2)
return;
if (vertical2Point.Count != 2)
return;
// 定义十字型的线段
var horizontalStart = horizontal2Point[0];
var horizontalEnd = horizontal2Point[1];
var verticalStart = vertical2Point[0];
var verticalEnd = vertical2Point[1];
// 创建路径,并添加线段
var geometry = new StreamGeometry();
using (var geometryContext = geometry.Open())
{
geometryContext.BeginFigure(horizontalStart, false, false);
geometryContext.LineTo(horizontalEnd, true, false);
geometryContext.BeginFigure(verticalStart, false, false);
geometryContext.LineTo(verticalEnd, true, false);
}
dc.DrawGeometry(brush, p, geometry);
}
/// <summary>
/// 绘制圆弧
/// </summary>
/// <param name="dc"></param>
/// <param name="center">中心点</param>
/// <param name="startAngle">其实角度</param>
/// <param name="endAngle">截止角度</param>
/// <param name="radius">半径</param>
void DrawArc(DrawingContext dc, Pen pen, Point center, double startAngle, double endAngle, double radius)
{
// 使用ArcSegment绘制圆弧
var arcGeometry = new PathGeometry();
var arcFigure = new PathFigure
{
StartPoint = new Point(center.X + radius * Math.Cos(startAngle * Math.PI / 180), center.Y + radius * Math.Sin(startAngle * Math.PI / 180)),
IsClosed = false,
IsFilled = true
};
arcFigure.Segments.Add(new ArcSegment(new Point(center.X + radius * Math.Cos(endAngle * Math.PI / 180), center.Y + radius * Math.Sin(endAngle * Math.PI / 180)), new Size(radius, radius), 0, Math.Abs(endAngle - startAngle) > 180, SweepDirection.Clockwise, true));
arcGeometry.Figures.Add(arcFigure);
// 绘制圆弧
dc.DrawGeometry(Brushes.Transparent, pen, arcGeometry);
}