CAD.NET API一日一练(5)图块改色
本帖最后由 mrhvslisp 于 2011-11-4 15:05 编辑代码已更正,感谢sailorcwx 的指导,谢谢!!!
#region//图块改色
public void BlockColor()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
TypedValue[] filter = new TypedValue;
filter = new TypedValue(0, "insert");
SelectionFilter ssfilter = new SelectionFilter(filter);
PromptSelectionResult ssresult = ed.GetSelection(ssfilter);
if (ssresult.Status != PromptStatus.OK)
{
return;
}
PromptIntegerOptionsintoptions=new PromptIntegerOptions ("");
intoptions.Message = "\n请指定颜色";
intoptions.AllowArbitraryInput = false;
intoptions.AllowNone = true ;
intoptions.DefaultValue = 1;
intoptions.AllowNegative = false;
PromptIntegerResult intresult=ed.GetInteger(intoptions);
if (intresult .Status!=PromptStatus.OK)
{
return;
}
List <BlockTableRecord> list=new List<BlockTableRecord> ();
list = getlist(db, ssresult,intresult,list);
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
foreach (BlockTableRecord blkr in list)
{
ModifyColor(blkr, trans, bt, intresult);
}
trans.Commit();
}
}
//获取块定义集合(块表记录集合)
public List<BlockTableRecord> getlist(Database db, PromptSelectionResult ssresult,PromptIntegerResult intresult,List <BlockTableRecord> list)
{
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
foreach (ObjectId id in ssresult.Value.GetObjectIds())
{
BlockReference ent = trans.GetObject(id, OpenMode.ForWrite) as BlockReference;
ent.ColorIndex = intresult.Value;
BlockTableRecord blkr = trans.GetObject(bt, OpenMode.ForRead) as BlockTableRecord;
if (!list.Contains(blkr))
{
list.Add(blkr);
}
}
trans.Commit();
return list;
}
}
//对块定义改色
public void ModifyColor(BlockTableRecord blkr, Transaction trans, BlockTable bt, PromptIntegerResult intresult)
{
BlockTableRecordEnumerator enu = blkr.GetEnumerator();//获取块枚举器
while (enu.MoveNext())
{
Entity ent = (Entity)trans.GetObject(enu.Current, OpenMode.ForWrite);
ent.ColorIndex = intresult.Value;
if (ent is BlockReference)
{
ent.ColorIndex = intresult.Value;
blkr = trans.GetObject(bt[((BlockReference)ent).Name], OpenMode.ForWrite)as BlockTableRecord;
ModifyColor(blkr, trans, bt, intresult);
}
}
}
本帖最后由 sailorcwx 于 2011-11-4 14:42 编辑
我不是版主,不过我分析一下
你最后的ent.BlockName得到的其实是上一层的块参照名称,打个比方,你的"块1“内嵌"块2",那么你的
ent.BlockName返回的是"块1",ent.Name才是它的块名"块2",所以导致了死循环,因此应该添加一个转换
BlockReference ent1 = (BlockReference)ent;
然后用ent.Name来读取块名
blkr = trans.GetObject(bt, OpenMode.ForWrite)as BlockTableRecord; sailorcwx 发表于 2011-11-4 14:39 static/image/common/back.gif
我不是版主,不过我分析一下
你最后的ent.BlockName得到的其实是上一层的块参照名称,打个比方,你的"块1“ ...
哈哈,完全正确,学习了,感谢老师指导 好贴,一定支持。 好贴,一定支持。
页:
[1]