C#实战之CAD二次开发008:常用工具类分享

一、画图类

    public static class DrawTools
    {
        public static ObjectId AddToModelSpace(this Database db, Entity ent, string layer)
        {
            ObjectId entId;//用于返回添加到模型空间中的实体ObiectId
            //定义一个指向当前数据库的事务处理
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                //以写的方式打开模型空间块表记录
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                //指定要添加的實體的圖層
                ent.Layer = layer;
                entId = btr.AppendEntity(ent);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(ent, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理
            }
            return entId;//返回实体的objectid
        }
        // 绘制直线
        public static void DrawLine(Point3d startPoint, Point3d endPoint, string layer, LineWeight lineWeight)
        {
            // 獲取當前活動圖形数據庫
            Database db = HostApplicationServices.WorkingDatabase;
            Line line = new Line(startPoint, endPoint);//新建一條直線對象
            // 定義一個指向當前数據庫的事務處里,以添加直線
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); // 以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                line.Layer = layer;
                line.LineWeight = lineWeight;
                btr.AppendEntity(line); // 以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(line, true); // 把对象添加到事务处理中
                trans.Commit(); // 提交事务处理
            }
        }
        // 畫圓
        public static void CreateCircle(Point3d pt1, Point3d pt2, Point3d pt3, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Circle circle = new Circle();
            //先判斷三點是否共線,得到pt1點指向pt2、pt2點的矢量
            Vector3d va = pt1.GetVectorTo(pt2);
            Vector3d vb = pt1.GetVectorTo(pt3);

            //如兩矢量夾角為0或180度(π弧度),則三點共線
            if (va.GetAngleTo(vb) == 0 | va.GetAngleTo(vb) == Math.PI)
            {

            }
            else
            {
                //創建一個幾何類的圓弧對象
                CircularArc3d geArc = new CircularArc3d(pt1, pt2, pt3);
                //將圓弧對象的圓心和半徑賦值給圓
                circle.Center = geArc.Center;
                circle.Radius = geArc.Radius;
                circle.Layer = layer;
            }
            //定義一個指向當前数據庫的事務處里,以添加
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                btr.AppendEntity(circle);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(circle, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理
            }
        }
        public static void CreateCircle(Point3d center, double radius, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Circle circle = new Circle();
            circle.Center = center;
            circle.Radius = radius;
            circle.Layer = layer;
            //定義一個指向當前数據庫的事務處里,以添加
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                btr.AppendEntity(circle);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(circle, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理
            }
        }
    }

二、几何计算类

    public static class GeTools
    {
        // 計算兩個點的中點
        public static Point3d MidPoint(Point3d pt1, Point3d pt2)
        {
            return new Point3d((pt1.X + pt2.X) / 2, (pt1.Y + pt2.Y) / 2, (pt1.Z + pt2.Z) / 2);
        }
        // 將極座标轉換為Point3d對象
        public static Point3d PolarPoint(this Point3d point, double angle, double dist)
        {
            return new Point3d(point.X + dist * Math.Cos(angle), point.Y + dist * Math.Sin(angle), point.Z);
        }
        // 角度转弧度
        public static double DegreeToRadian(double degree)
        {
            return degree * Math.PI / 180;
        }
    }

三、标注类

    public static class DimensionTools
    {
        private static Database db = HostApplicationServices.WorkingDatabase;
        //水平标注,主要用於标注頸徑(不用將主尺寸下拉)
        //當标注需要放在标注線外面時,(A1,A2)是將标注放在A1的左邊,而(A2,A1)可以將标注放在A2的右邊
        public static void addHorizonRotatedDimension(Point3d pt1, Point3d pt2, string text, double distance, double textHeight)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    RotatedDimension dimRotated = new RotatedDimension();
                    dimRotated.XLine1Point = pt1;
                    dimRotated.XLine2Point = pt2;
                    dimRotated.DimLinePoint = GeTools.MidPoint(pt1, pt2).PolarPoint(-Math.PI / 2, distance);
                    dimRotated.DimensionText = text; // <>代表标注的主尺寸,此處在标注線上插入文字
                    dimRotated.Dimtxt = textHeight;
                    dimRotated.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimRotated, "Dim");
                }
            }
        }
        // 垂直标注
        public static void addVerticalRotatedDimension(Point3d pt1, Point3d pt2, string text, double distance)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    RotatedDimension dimRotated = new RotatedDimension();
                    dimRotated.Rotation = Math.PI / 2;
                    dimRotated.XLine1Point = pt1;
                    dimRotated.XLine2Point = pt2;
                    dimRotated.DimLinePoint = GeTools.MidPoint(pt1, pt2).PolarPoint(0, distance);
                    dimRotated.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimRotated.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimRotated, "Dim");
                }
            }
        }
        // 創建對齊标注
        public static void addAlignedDimension(Point3d pt1, Point3d pt2, string text, string layer)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    AlignedDimension dimAligned = new AlignedDimension();
                    dimAligned.XLine1Point = pt1;
                    dimAligned.XLine2Point = pt2;
                    dimAligned.DimLinePoint = GeTools.MidPoint(pt1, pt2).PolarPoint(Math.PI / 2, 10);
                    dimAligned.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimAligned.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimAligned, layer);
                }
            }
        }
        // 創建半徑标注
        public static void addRadialDimension(Point3d center, string text, double R, Int32 len, double textHeight)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    RadialDimension dimRadial = new RadialDimension();
                    dimRadial.Center = center;//圓心
                    //用於附著引線的圓或圓弧上的點 
                    //30是角度,15是圓弧的半徑
                    dimRadial.ChordPoint = center.PolarPoint(GeTools.DegreeToRadian(len), R);
                    dimRadial.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimRadial.LeaderLength = 5;//引線長度
                    dimRadial.DimensionStyle = db.Dimstyle;
                    dimRadial.Dimtxt = textHeight;
                    db.AddToModelSpace(dimRadial, "dim");
                }
            }
        }
        // 創建直徑标注       
        public static void addDiametricDimension(Point3d center, string text, string layer)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    DiametricDimension dimDiametric = new DiametricDimension();
                    //指定圓心,引線角度和長度
                    dimDiametric.ChordPoint = center.PolarPoint(GeTools.DegreeToRadian(45), 10);//第一個箭頭所在的點
                    dimDiametric.FarChordPoint = center.PolarPoint(GeTools.DegreeToRadian(-135), 10);//第二個箭頭所在的點
                    dimDiametric.LeaderLength = 0;//從chordPoint到注解文字或折?處的長度
                    dimDiametric.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimDiametric.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimDiametric, layer);
                }
            }
        }
        // 創建角度标注
        public static void addDiametricDimension(Point3d start, Point3d center, Point3d end, string text, double distance)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    Point3AngularDimension dimLineAngular = new Point3AngularDimension();
                    //圓或圓弧的圓心、或兩個尺寸界線間的共有頂點的座标
                    dimLineAngular.CenterPoint = center;
                    dimLineAngular.XLine1Point = start;
                    dimLineAngular.XLine2Point = end;
                    dimLineAngular.ArcPoint = center.PolarPoint(GeTools.DegreeToRadian(135), distance);
                    dimLineAngular.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    if (text.Length > 8)
                    {
                        dimLineAngular.Dimtxt = 2;
                    }
                    dimLineAngular.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimLineAngular, "Dim");
                }
            }
        }
        // 水平角度
        public static void addDiametricDimension2(Point3d start1, Point3d start2, Point3d end1, Point3d end2, string text, double distance, Point3d TextPosition)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    LineAngularDimension2 dimLineAngular = new LineAngularDimension2();
                    // 圓或圓弧的圓心、或兩個尺寸界線間的共有頂點的座标
                    dimLineAngular.XLine1Start = start1;
                    dimLineAngular.XLine2Start = start2;
                    dimLineAngular.XLine1End = end1;
                    dimLineAngular.XLine2End = end2;
                    dimLineAngular.ArcPoint = GeTools.MidPoint(start1, start2).PolarPoint(GeTools.DegreeToRadian(90), distance);
                    dimLineAngular.Dimtmove = 1;  // 设置标注形式为文字偏移
                    dimLineAngular.Dimasz = 2; // 设置箭头大小
                    dimLineAngular.TextPosition = TextPosition;
                    dimLineAngular.DimensionText = text; // <>代表标注的主尺寸,此處在标注線上插入文字
                    if (text.Length > 8)
                    {
                        dimLineAngular.Dimtxt = 2;
                    }
                    dimLineAngular.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimLineAngular, "Dim");
                }
            }
        }
        // 垂直角度
        public static void addDiametricDimension3(Point3d start1, Point3d start2, Point3d end1, Point3d end2, string text, double distance)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    LineAngularDimension2 dimLineAngular = new LineAngularDimension2();
                    //圓或圓弧的圓心、或兩個尺寸界線間的共有頂點的座标
                    dimLineAngular.XLine1Start = start1;
                    dimLineAngular.XLine2Start = start2;
                    dimLineAngular.XLine1End = end1;
                    dimLineAngular.XLine2End = end2;
                    dimLineAngular.ArcPoint = GeTools.MidPoint(start1, start2).PolarPoint(GeTools.DegreeToRadian(0), distance);
                    dimLineAngular.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    if (text.Length > 8)
                    {
                        dimLineAngular.Dimtxt = 2;
                    }

                    dimLineAngular.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimLineAngular, "Dim");
                }
            }
        }
        public static void addDiametricDimension3(Point3d start1, Point3d start2, Point3d end1, Point3d end2, string text, double distance, double textHeight)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    LineAngularDimension2 dimLineAngular = new LineAngularDimension2();
                    //圓或圓弧的圓心、或兩個尺寸界線間的共有頂點的座标
                    dimLineAngular.XLine1Start = start1;
                    dimLineAngular.XLine2Start = start2;
                    dimLineAngular.XLine1End = end1;
                    dimLineAngular.XLine2End = end2;
                    dimLineAngular.ArcPoint = GeTools.MidPoint(start1, start2).PolarPoint(GeTools.DegreeToRadian(0), distance);
                    dimLineAngular.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimLineAngular.Dimtxt = textHeight;
                    dimLineAngular.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimLineAngular, "Dim");
                }
                trans.Commit();
            }
        }
        // 創建座标标注
        public static void addCoordinateDimension(bool isView, Point3d pt1, Point3d pt2, string text, double length, double textHeight)
        {
            using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                if (text != "")
                {
                    //創建顯示X軸值的座标标注
                    /*OrdinateDimension dimX = new OrdinateDimension();                
                    dimX.UsingXAxis = true;//顯示X軸值
                    dimX.DefiningPoint = pt1;//标注點
                    //指定引線終點,即标注文字顯示的位置
                    dimX.LeaderEndPoint = pt2.PolarPoint(-Math.PI/2, 10);
                    dimX.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimX.DimensionStyle = db.Dimstyle;
                    db.AddToModelSpace(dimX, "Dim");*/
                    //創建顯示Y軸值的座标标注
                    OrdinateDimension dimY = new OrdinateDimension();
                    dimY.UsingXAxis = isView;//顯示Y軸值
                    dimY.DefiningPoint = pt1;//标注點
                    //指定引線終點,即标注文字顯示的位置
                    dimY.LeaderEndPoint = pt2.PolarPoint(0, length);
                    dimY.DimensionText = text;//<>代表标注的主尺寸,此處在标注線上插入文字
                    dimY.DimensionStyle = db.Dimstyle;
                    dimY.Dimtxt = textHeight;
                    db.AddToModelSpace(dimY, "Dim");
                }
            }
        }
        // 多重引線
        public static void AddMLeader(Point3d pt1, Point3d pt2, Point3d pt3, string text1, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //創建3個點分別表示引線的終點和頭點
                Point3d ptStart1 = pt1;
                Point3d ptEnd = pt2;
                Point3d ptStart2 = pt3;
                MText mtext = new MText();//新建多行文本
                mtext.Contents = text1;//文本內容
                mtext.TextHeight = 2.2;//文本高度
                MLeader mleader = new MLeader();//創建一個引線對象
                int leaderIndex = mleader.AddLeader();//添加引線束,引線束由基線和一些單引線構成
                int lineIndex = mleader.AddLeaderLine(leaderIndex);//在引線束中添加單引線
                mleader.AddFirstVertex(lineIndex, pt1);//單引線中添加引線頭點
                mleader.AddLastVertex(lineIndex, pt2);//單引線中添加引線終點
                lineIndex = mleader.AddLeaderLine(leaderIndex);
                mleader.AddFirstVertex(lineIndex, pt3);
                mleader.ContentType = ContentType.MTextContent;//設置引線的註釋為多行文本
                mleader.MText = mtext;
                mleader.ArrowSize = 2.5;//引線長度
                mleader.DoglegLength = 0.2;
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                mleader.Layer = layer;
                btr.AppendEntity(mleader);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(mleader, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理      
            }
        }
        // 引线标注
        public static void AddLeader(Point3d location, Point3d TextLocation, string text, string layer, double textHeight)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                MText mtext = new MText();//新建多行文本
                mtext.Contents = text;//文本內容
                mtext.Location = TextLocation;
                mtext.TextHeight = textHeight;//文本高度
                db.AddToModelSpace(mtext, layer);
                Leader leader = new Leader();//創建一個引線對象
                leader.AppendVertex(location);
                leader.AppendVertex(TextLocation);
                db.AddToModelSpace(leader, layer);
                leader.Dimgap = 0.3; // 設置引線的文字偏移
                leader.Dimasz = 2.5; // 設置引線的箭頭大小
                leader.Annotation = mtext.ObjectId;
                leader.EvaluateLeader();
                trans.Commit();//提交事务处理      
            }
        }
        // 形位公差
        // 添加CreateTolerance函数用於設置形位公差值
        public static void CreateTolerance(this FeatureControlFrame frame, string geometricSym, string torlerance, string firstDatum)
        {
            if (frame == null) return;//特徵框對象必須已定義,否則返回
            //設置形位公差值,各組成部份用豎線(%%v)分隔
            frame.Text = geometricSym + "%%v" + torlerance + "%%v" + firstDatum;
        }
        public struct DimFormatCode
        {
            public static readonly string Bounce = @"{\Fgdt;" + "h}"; //跳動度
            public static readonly string Lkd = @"{\Fgdt;" + "k}"; //輪廓度
            public static readonly string Tzd = @"{\Fgdt;" + "r}"; //同轴度
        }
        // 标注跳动
        public static void AddTolerance(Point3d pt1, string gc, double size, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //創建一個形位公差特徵控制框
                FeatureControlFrame frame = new FeatureControlFrame();
                //形位公差的幾何特徵為跳動度
                string geometricSym = DimFormatCode.Bounce;
                //形位公差值
                string torlerance = gc;
                //形位公差的第一級基準符號
                string firstDatum = "A";
                //設置形位公差特徵控制框的內容為形位公差
                frame.CreateTolerance(geometricSym, torlerance, firstDatum);
                frame.Location = pt1;//控制框的位置
                frame.Dimscale = size;//控制框的大小
                frame.Layer = layer;
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                btr.AppendEntity(frame);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(frame, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理      
            }
        }
        // 标注轮廓度
        public static void AddTolerance1(Point3d pt1, string torlerance, string torlerance1, double size, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //創建一個形位公差特徵控制框
                FeatureControlFrame frame = new FeatureControlFrame();
                //形位公差的幾何特徵為跳動度
                string geometricSym = DimFormatCode.Lkd;
                //形位公差的第一級基準符號
                //string firstDatum = "A";
                //設置形位公差特徵控制框的內容為形位公差
                frame.CreateTolerance(geometricSym, torlerance, torlerance1);
                frame.Location = pt1;//控制框的位置
                frame.Dimscale = size;//控制框的大小
                frame.Layer = layer;
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);//以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                btr.AppendEntity(frame);//以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(frame, true);//把对象添加到事务处理中
                trans.Commit();//提交事务处理      
            }
        }
        // 标注同轴度
        public static void AddTolerance2(Point3d pt1, string torlerance, string torlerance1, double size, string layer)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 創建一個形位公差特徵控制框
                FeatureControlFrame frame = new FeatureControlFrame();
                // 形位公差的幾何特徵為跳動度
                string geometricSym = DimFormatCode.Tzd;
                // 形位公差的第一級基準符號
                // string firstDatum = "A";
                // 設置形位公差特徵控制框的內容為形位公差
                frame.CreateTolerance(geometricSym, torlerance, torlerance1);
                frame.Location = pt1; // 控制框的位置
                frame.Dimscale = size; // 控制框的大小
                frame.Layer = layer;
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); // 以读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                btr.AppendEntity(frame); // 以图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(frame, true); // 把对象添加到事务处理中
                trans.Commit(); // 提交事务处理      
            }
        }
    }

四、图块类

    public static class BlockTools
    {
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle)
        {
            ObjectId blockRefId;//存储要插入的块参照的Id
            Database db = spaceId.Database;//获取数据库对象
            //以读的方式打开块表
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
            //如果没有blockName表示的块,则程序返回
            if (!bt.Has(blockName)) return ObjectId.Null;
            //以写的方式打开空间(模型空间)
            BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite);
            //创建一个块参照并设置插入点
            BlockReference br = new BlockReference(position, bt[blockName]);
            br.ScaleFactors = scale;//设置块参照的缩放比例
            br.Layer = layer;//设置块参照的层名
            br.Rotation = rotateAngle;//设置块参照的旋转角度
            blockRefId = space.AppendEntity(br);//在空间中加入创建的块参照
            //通知事务处理加入创建的块参照
            db.TransactionManager.AddNewlyCreatedDBObject(br, true);
            space.DowngradeOpen();//为了安全,将块表状态改为读
            return blockRefId;//返回添加的块参照的Id
        }
        public static ObjectId CreateStyle(string name, string smallfont, string bigfont, double height, double xscale)
        {
            // ObjectId textstyleid = new ObjectId();
            Database dbH = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = dbH.TransactionManager.StartTransaction())
            {
                TextStyleTable TST = trans.GetObject(dbH.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                ObjectId id = GetIdFromSymbolTable(TST, name);
                if (id == ObjectId.Null)
                {
                    TextStyleTableRecord TSTR = new TextStyleTableRecord();
                    TSTR.Name = name;
                    TSTR.FileName = smallfont;
                    TSTR.BigFontFileName = bigfont;
                    TSTR.TextSize = height;
                    TSTR.XScale = xscale;
                    TST.UpgradeOpen();
                    id = TST.Add(TSTR);
                    trans.AddNewlyCreatedDBObject(TSTR, true);
                }
                return id;
            }
        }
        public static ObjectId GetIdFromSymbolTable(SymbolTable st, string key)
        {
            Database dbH = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = dbH.TransactionManager.StartTransaction())
            {
                if (st.Has(key))
                {
                    ObjectId idres = st[key];
                    if (!idres.IsErased)
                        return idres;
                    foreach (ObjectId id in st)
                    {
                        if (!id.IsErased)
                        {
                            SymbolTableRecord str = (SymbolTableRecord)trans.GetObject(id, OpenMode.ForRead);
                            if (str.Name == key)
                                return id;
                        }
                    }
                }
            }
            return ObjectId.Null;
        }
        public static void InsertBlockFromDwg(string blockName, string fileName, Point3d position, Scale3d scale)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;

            using (Database db = new Database(false, true))
            {
                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    //如果文件存在
                    if (File.Exists(fileName))
                    {
                        db.ReadDwgFile(fileName, FileShare.Read, true, null);
                        db.CloseInput(true);
                        string name = blockName;
                        ObjectId btrId = doc.Database.Insert(name, db, false);
                        //獲取数據庫塊表對象
                        BlockTable bt = (BlockTable)trans.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                        //打開数據庫模型空間塊表記錄對象
                        BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        using (BlockReference br = new BlockReference(position, btrId))
                        {
                            br.ScaleFactors = scale;//设置块参照的缩放比例
                            btr.AppendEntity(br);
                            trans.AddNewlyCreatedDBObject(br, true);
                        }
                    }
                    trans.Commit();
                }
            }
        }
    }

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值