CAD 二次开发 图层操作(1)创建图层

版权声明:转载请注明出处,最好发邮件告知。谢谢 https://blog.csdn.net/luckysiesteven/article/details/11777457

CAD二次开发的资料比较少,除了李冠亿先生的《深居浅出AutoCAD二次开发》这本书之外,目前没有找到合适的参考资料。现将自己工作中用的的一些方法贴出来。方便各位网友快速入门。

 

#region 添加图层

        /// <summary>
        /// 添加图层
/// </summary>
        /// <param name="layName"></param>
/// <param name="layColor"></param>
        private ObjectId AddLayer(string layName, short layColor)
        {
            ObjectId oidReturn = new ObjectId(); ;
            using (Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Database database = HostApplicationServices.WorkingDatabase;
                Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    try
                    {
                        ObjectId id;
                        LayerTable table = transaction.GetObject(database.LayerTableId, OpenMode.ForWrite) as LayerTable;
                        LayerTableRecord record = new LayerTableRecord();
                        if (table.Has(layName))
                        {
                            id = table.Id;
                            record = transaction.GetObject(id, OpenMode.ForWrite) as LayerTableRecord;
                            record.IsOff = false;
                            record.IsLocked = false;
                            if (id != database.Clayer)
                            {
                                record.IsFrozen = false;
                            }
                        }
                        else
                        {
                            record.Name = layName;
                            id = table.Add(record);
                            transaction.AddNewlyCreatedDBObject(record, true);
                        }
                        record.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByColor, layColor);
                        database.Clayer = id;
                        oidReturn = id;
                        transaction.Commit();
                    }
                    catch (Exception exception)
                    {

                        editor.WriteMessage("Error in addLayer2(): " + exception.Message);
                    }

                }
                return oidReturn;
            }
        }

        #endregion

如上述代码所示:

输入参数为:图层名称,和图层颜色

实现该功能的思路为:

锁定图档,

开启事务

获得当前图档的图层表(LayerTable);

像操作关系数据库那样创建一条图层表的新 纪录;

对新纪录赋予图层名称,定义图层颜色;

通过添加到图层表,获得记录主键;

通过事务,将新图层记录添加到图当中;

提交事务;

完成。

 

 如有问题:请加qq1419226548或QQmail给我。 若转载,请注明出处。谢谢。

展开阅读全文

没有更多推荐了,返回首页