CAD二次开发IFoxCAD框架系列(26)- 分段测量多段线长度和计算多边形的面积
#region 分段测量多段线长度
private static double textHight = 10;
[CommandMethod(nameof(PolylineDemo))]
public void PolylineDemo()
{
using var tr = new DBTrans();
if(!tr.LayerTable.Has("标注"))
{
tr.LayerTable.Add("标注",1);
}
var pso = new PromptSelectionOptions()
{
MessageForAdding = "\n选择要测量的多段线或【设置字高(S)】"
};
pso.Keywords.Add("S"," ");
OpFilter sf = OpFilter.Build(e=>e.Dxf(0)== "LWPOLYLINE");
pso.KeywordInput += (o, s) =>
{
switch (s.Input.ToUpper())
{
case "S":
var r2 = Env.Editor.GetDouble("\n请输入字高<"+textHight+">");
if (r2.Status == PromptStatus.OK && r2.Value>0)
{
textHight = r2.Value;
}
break;
case " ":
return;
}
};
//开始选择
var r1 = Env.Editor.GetSelection(pso,sf);
if (r1.Status != PromptStatus.OK)
{
return;
}
//获取到所有的多段线
var polylines = r1.Value.GetEntities<Polyline>();
foreach (var polyline in polylines)
{
for (int i = 0; i < polyline.NumberOfVertices; i++)
{
//获取当前线段的类型
var st = polyline.GetSegmentType (i);
if(st == SegmentType.Line)//直线
{
var cur = polyline.GetLineSegmentAt(i).ToCurve();
AddText(cur, tr); //添加文字
}else if(st == SegmentType.Arc)//圆弧
{
var cur = polyline.GetArcSegmentAt(i).ToCurve();
AddText(cur, tr); //添加文字
}
}
if (polyline.Closed)
{
var ppr = Env.Editor.GetPoint("\n选择多边形面积计算结果的位置");
if (r1.Status != PromptStatus.OK)
{
return;
}
var point3d = ppr.Value;
GetArea(polyline, point3d,tr);
}
}
}
private void AddText(Curve curve,DBTrans tr)
{
//拿到线段起点和终点
var pt1 = curve.StartPoint;
var pt2 = curve.EndPoint;
var length = curve.GetLength();
//计算角度
var angle1 = pt1.GetAngle(pt2);
//计算文字偏移角度
var angle2 = angle1 + Math.PI*0.5;
var textPoint = curve.GetPointAtDist(length*0.5).Polar(angle2,textHight);
var text = new DBText()
{
Position = textPoint,
TextString = (length/1000).ToString("0.00"),
HorizontalMode = TextHorizontalMode.TextCenter,
VerticalMode = TextVerticalMode.TextVerticalMid,
AlignmentPoint = textPoint,
WidthFactor = 0.7,
Layer = "标注",
Height = textHight
};
//设置文字角度和线平行并向上
text.Rotation = angle1 > Math.PI*0.5 && angle1 <= Math.PI*1.5 ? angle2 + Math.PI : angle1;
tr.CurrentSpace.AddEntity(text);
}
/// <summary>
/// 计算多边形的面积
/// </summary>
/// <param name="polyline">要计算的多边形对象</param>
/// <param name="point">放置的点</param>
/// <param name="tr"></param>
public void GetArea(Polyline polyline,Point3d point,DBTrans tr)
{
if (polyline.Closed)
{
List<Point2d> pointList = polyline.GetPoints()
.Select(point => point.Point2d()).ToList();
double area = Math.Abs(GeometryEx.GetArea(pointList));
var text = new DBText()
{
Position = point,
TextString = "当前多边形的面积为:" + (area / 1000).ToString("0.00"),
HorizontalMode = TextHorizontalMode.TextCenter,
VerticalMode = TextVerticalMode.TextVerticalMid,
AlignmentPoint = point,
WidthFactor = 0.7,
Layer = "标注",
Height = textHight,
};
var sts = tr.TextStyleTable;
if (sts.Has("宋体"))
{
var textStyle = tr.TextStyleTable.GetRecord("宋体");
if (textStyle != null)
{
text.TextStyleId = textStyle.Id;
}
}
tr.CurrentSpace.AddEntity(text);
}
}
#endregion
如果遇到中文字体乱码,可以如下操作,选择字体为宋体。