AutoCAD C#

[AutoCAD C#]폴리선의 좌표를 표시한다.

데브프로그라 2024. 12. 21. 23:34
반응형

AutoCAD에서 폴리선들을 선택하고 해당 폴리선의 꼭지점들의 XY 좌표를 보여주는 C# 코드를 작성해 보겠습니다. 
이 코드는 AutoCAD .NET API를 사용하며, AutoCAD 플러그인 형태로 실행될 수 있습니다.

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;

namespace PolylineCoordinates
{
    public class Commands
    {
        [CommandMethod("GetPolylineCoords")]
        public static void GetPolylineCoordinates()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 폴리선 선택 프롬프트
            PromptSelectionOptions selectionOptions = new PromptSelectionOptions();
            selectionOptions.MessageForSelect = "\n폴리선을 선택하세요: ";
            selectionOptions.SingleOnly = false; // 여러 폴리선 선택 가능

            PromptSelectionResult selectionResult = ed.GetSelection(selectionOptions);

            if (selectionResult.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\n선택이 취소되었습니다.");
                return;
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                SelectionSet selectionSet = selectionResult.Value;
                
                foreach (ObjectId objectId in selectionSet.GetObjectIds())
                {
                   Entity entity = tr.GetObject(objectId, OpenMode.ForRead) as Entity;

                    if (entity is Polyline polyline)
                    {
                       ed.WriteMessage($"\n폴리선 ID: {objectId.Handle}");

                        for(int i = 0; i < polyline.NumberOfVertices; i++)
                        {
                            Point3d vertex = polyline.GetPoint3dAt(i);
                            ed.WriteMessage($"\n    꼭지점 {i + 1}: X = {vertex.X}, Y = {vertex.Y}");
                        }
                    }
                    else
                    {
                        ed.WriteMessage($"\n선택한 객체 ID {objectId.Handle}은(는) 폴리선이 아닙니다.");
                    }
                }
                tr.Commit();
            }
        }
    }
}

위와 같이 코딩하시고, 실행하여 테스트 하시면 됩니다.

반응형