1、说明
动态块具有灵活性和智能性,用户在操作时可以轻松地更改图形中的动态块参照,可以通过自定义夹点或自定义特性来操作动态块参照中的几何图形,这使得用户可以根据需要在位调整块,而不用搜索另一个块以插入或者重定义现有的块。
2、思路
在图形中,插入动态块并设置动态属性的步骤如下:
1)插入动态块;
1 /// <summary> 2 /// 插入带属性的参照快 3 /// </summary> 4 /// <param name="spaceId">空间的ID</param> 5 /// <param name="layer">块要加入的图层名</param> 6 /// <param name="blockName">快参照所属的快名</param> 7 /// <param name="postion">插入点</param> 8 /// <param name="scale">缩放比例</param> 9 /// <param name="rotateAngle">旋转角度</param> 10 /// <param name="attNameValues">属性名称与取值</param> 11 /// <returns></returns> 12 public static ObjectId InsertBlockrefence(this ObjectId spaceId, string layer, string blockName, Point3d postion, Scale3d scale, double rotateAngle, Dictionary<string, string> attNameValues) 13 { 14 // 获取数据库对象 15 Database db = spaceId.Database; 16 //以读的方式打开块表 17 BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; 18 //如果没有blockName d的块,则程序返回 19 if (!bt.Has(blockName)) 20 21 return ObjectId.Null;//如果没有blockName的块,程序返回 22 //以写的模式打开空间 23 BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); 24 //获取块表的记录ID 25 ObjectId btrId = bt[blockName]; 26 //打开块表记录 27 BlockTableRecord record = btrId.GetObject(OpenMode.ForRead) as BlockTableRecord; 28 //创建一个快参照并设置插入点 29 BlockReference br = new BlockReference(postion, bt[blockName]); 30 31 br.ScaleFactors = scale; 32 33 br.Layer = layer; 34 br.Rotation = rotateAngle; 35 36 space.AppendEntity(br); 37 //判断块表记录是否包含属性定义 38 if (record.HasAttributeDefinitions) 39 { 40 //若包含,则遍历属性定义 41 foreach (ObjectId id in record) 42 { 43 //检查是否是属性定义 44 AttributeDefinition attDef = id.GetObject(OpenMode.ForRead) as AttributeDefinition; 45 46 if (attDef != null) 47 { 48 49 //创建一个新的属性对象 50 AttributeReference attribute = new AttributeReference(); 51 //从属性定义获取属性对象的对象特性 52 attribute.SetAttributeFromBlock(attDef, br.BlockTransform); 53 attribute.Rotation = attDef.Rotation; 54 55 attribute.Position = attDef.Position.TransformBy(br.BlockTransform); 56 57 attribute.AdjustAlignment(db); 58 //判断是否包含指定的属性名称 59 if (attNameValues.ContainsKey(attDef.Tag.ToUpper())) 60 { 61 62 //设置属性值 63 attribute.TextString = attNameValues[attDef.Tag.ToUpper()].ToString(); 64 65 } 66 // 向块参照添加属性对象 67 br.AttributeCollection.AppendAttribute(attribute); 68 db.TransactionManager.AddNewlyCreatedDBObject(attribute, true); 69 70 } 71 } 72 } 73 db.TransactionManager.AddNewlyCreatedDBObject(br, true); 74 return br.ObjectId;//返回添加的快参照的ID 75 }