外部参照

外部参照在CAD绘图中也扮演着重要角色,设计人员经常将外部图纸作为参照载入当前图纸,用于比对图纸信息或成果组织。
本文针对外部参照,封装加载、卸载、删除、查询接口,卸载接口尤其值得注意。

加载外部参照

1
2
3
4
5
6
7
8
9
10
11
12
public static ObjectId AttachXref(this Database db, string dwgPath, string xrefName, Point3d insertPoint)
{
ObjectId refId = db.AttachXref(dwgPath, xrefName);
if (!refId.IsNull)
{
var blockRef = new BlockReference(insertPoint, refId);
db.AddEntity(blockRef);
DwgOperators.ThisEditor.UpdateScreen();
return blockRef.ObjectId;
}
return ObjectId.Null;
}

卸载外部参照

注意:卸载外部参照时,最好一并删除,否则每次打开图形会提示外部参照未加载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public static bool UnloadXrefByName(this Database db, string xrefName)
{
bool flag = false;
using (Transaction tran = db.TransactionManager.StartTransaction())
{
BlockTable bt = tran.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
foreach (ObjectId id in bt)
{
BlockTableRecord btr = tran.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
if (btr.IsFromExternalReference && btr.Name == xrefName)
{
db.UnloadXrefs(new ObjectIdCollection(new ObjectId[] { id }));
db.DetachXref(id);
flag = true;
break;
}
}
tran.Commit();
}
DwgOperators.ThisEditor.UpdateScreen();
return flag;
}

public static bool SearchXrefByName(this Database db, string xrefName)
{
bool flag=false;
using (Transaction tran = db.TransactionManager.StartTransaction())
{
BlockTable bt = tran.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
foreach (ObjectId id in bt)
{
BlockTableRecord btr = tran.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
if (btr.IsFromExternalReference && btr.Name == xrefName)
{
flag = true;
break;
}
}
tran.Commit();
}
return flag;
}

查询外部参照

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void DeleteXrefs(this Database db)
{
if (db == null) return;
using (Transaction tran = db.TransactionManager.StartTransaction())
{
BlockTable bt = tran.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
List<ObjectId> ids = new List<ObjectId>();
foreach (ObjectId id in bt)
{
BlockTableRecord btr = tran.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
if (btr.IsFromExternalReference)
ids.Add(id);
}
foreach (ObjectId id in ids)
{
BlockTableRecord btr = tran.GetObject(id, OpenMode.ForWrite, true) as BlockTableRecord;
if (btr != null)
btr.Erase();
}
tran.Commit();
}
}

评论