Building Coder(Revit 二次開發) - 刪除導入的JPG和BMP圖片

原文鏈接:Remove Imported JPG and BMP Images

這個主題可以幫助我們更好地理解Revit是如何處理導入的文件,以及如何通過API刪除導入的文件。

提問:
我希望在Revit模型中刪除導入的JPG和BMP圖片。我嘗試使用 filtered emelent collector,應用 WhereElementIsNotElementType 方法,找到所有名稱以 ".jpg" 結尾的元素,
最後在一個獨立的循環中刪除它們。但是我的代碼始終無法實現目標。

回答:
你的方法確實無法工作。我做了一些測試,發現癥結在於你必須首先刪除 non-ElementType 元素,然後才能刪除對應的 ElementType 元素。
以下是我的完成代碼:
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;

FilteredElementCollector col = new FilteredElementCollector( doc ).WhereElementIsNotElementType();

List<ElementId> ids = new List<ElementId>();

foreach( Element e in col )
{
    if( ElementNameEndsWithJpg( e ) )
    {
        Debug.Print( Util.ElementDescription( e ) );
        ids.Add( e.Id );
    }
}

ICollection<ElementId> idsDeleted = null;
Transaction t;

int n = ids.Count;

if( 0 < n )
{
    using( t = new Transaction( doc ) )
    {
        t.Start( "Delete non-ElementType '.jpg' elements" );

        idsDeleted = doc.Delete( ids );

        t.Commit();
    }
}

int m = ( null == idsDeleted ) ? 0 : idsDeleted.Count;

Debug.Print( string.Format("Selected {0} non-ElementType element{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix( n ), m ) );

col = new FilteredElementCollector( doc ).WhereElementIsElementType();

ids.Clear();

foreach( Element e in col )
{
    if( ElementNameEndsWithJpg( e ) )
    {
        Debug.Print( Util.ElementDescription( e ) );
        ids.Add( e.Id );
    }
}

n = ids.Count;

if( 0 < n )
{
    using( t = new Transaction( doc ) )
    {
        t.Start( "Delete element type '.jpg' elements" );

        idsDeleted = doc.Delete( ids );

        t.Commit();
    }
}

m = ( null == idsDeleted ) ? 0 : idsDeleted.Count;

Debug.Print( string.Format("Selected {0} element type{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix( n ), m ) );

return Result.Succeeded;

爲了測試這段代碼,我新建了一個Revit模型並且插入一個圖片:jeremy_philippe_partha_jim.jpg。
測試日誌如下:
Raster Images <161178 jeremy_philippe_partha_jim.jpg>
Selected 1 non-ElementType element, 1 successfully deleted.

ElementType <161176 jeremy_philippe_partha_jim.jpg>
Raster Images <161177 jeremy_philippe_partha_jim.jpg>
Selected 2 element types, 2 successfully deleted.

這表明:Revit 爲每個插入的圖片創建兩個 ElementType 對象和一個 non-ElementType 對象。而且這些對象的 ElementId 是連續的整數。

包含這個新例程的 Building Coder Samples 可以在此下載:version 2012.0.97.0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章