private void InsertBlock(Document doc, Point3d insertionPoint, string blockName)
{
// 获取当前数据库
Database db = doc.Database;
// 开启事务
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 请求用户选择块的定义
BlockTable blockTable = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
// BlockTableRecord record = blockId.GetObject(OpenMode.ForRead) as BlockTableRecord;
BlockTableRecord modelSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
// 指定插入点
//Point3d insertionPoint = new Point3d(10, 10, 0); // 举例:插入点坐标 (10, 10, 0)
ObjectId blockId = blockTable[blockName];
// 创建块参照并插入到模型空间
BlockReference blockRef = new BlockReference(insertionPoint, blockId);
var test = blockRef.IsDynamicBlock;
modelSpace.AppendEntity(blockRef);
//判断块表记录是否包含属性
if (modelSpace.HasAttributeDefinitions)
{
foreach (ObjectId id in modelSpace)
{
//检查是否为属性定义
AttributeDefinition definition = id.GetObject(OpenMode.ForRead) as AttributeDefinition;
if (definition != null)
{
//创建一个新的属性对象
AttributeReference attr = new AttributeReference();
attr.SetAttributeFromBlock(definition, blockRef.BlockTransform);
attr.Rotation = blockRef.Rotation;
attr.Position = blockRef.Position.TransformBy(blockRef.BlockTransform);
attr.AdjustAlignment(db);
//判断是否包含了指定的属性名称
//if (vals.ContainsKey(definition.Tag.ToUpper()))
//{
// //设置属性值
// attr.TextString = vals[definition.Tag.ToUpper()].ToString();
//}
//向块参照添加属性对象
blockRef.AttributeCollection.AppendAttribute(attr);
trans.AddNewlyCreatedDBObject(attr, true);
}
}
}
trans.AddNewlyCreatedDBObject(blockRef, true);
// 提交事务
trans.Commit();
}
}