Solidworks的工程圖中圖塊的使用也比較頻繁苗沧。本文將給大家介紹Solidworks中與塊有關(guān)的類SketchBlockDefinition及SketchBlockInstance。從字面上理解可以看出炭晒,與塊定義有關(guān)的功能與SketchBlockDefinition相關(guān)待逞。相同的塊,可以被插入到工程圖文檔中的各張圖中网严,則每張圖中的塊即為一個塊的實(shí)例识樱。
實(shí)例1:創(chuàng)建塊
在打開的工程圖中,任意繪制塊所需的草圖屿笼,注釋牺荠,并將其全部選中,運(yùn)行如下程序驴一,即可自動將選中的元素做成塊休雌。
public static void CreateBlock(SldWorks SwApp, ModelDoc2 SwDoc, string BlockPath)
{
SketchManager SwSktManager = SwDoc.SketchManager;
MathUtility swMathUtility = SwApp.GetMathUtility();
double[] xyz = new double[] { 0,0, 0 };//插入點(diǎn)
MathPoint swMathPoint = swMathUtility.CreatePoint(xyz);
SketchBlockDefinition SwBlockDefinition = SwSktManager.MakeSketchBlockFromSelected(swMathPoint);//將選中的元素做成塊
if (SwBlockDefinition != null)
{
SwBlockDefinition.Save(BlockPath);
}
else
{
MessageBox.Show("建塊失敗,請先選擇需要做塊的元素");
}
}
運(yùn)行效果:
實(shí)例2:插入圖塊
本例中將在工程圖中插入同一個圖塊肝断,可以切換不同的圖紙杈曲,重復(fù)運(yùn)行,實(shí)現(xiàn)插入多個圖塊實(shí)例胸懈。
public static void InsertBlock(SldWorks SwApp, ModelDoc2 SwDoc,string BlockPath)
{
string BlockName = BlockPath.Substring(BlockPath.LastIndexOf(@"\")+1, BlockPath.LastIndexOf(".")- BlockPath.LastIndexOf(@"\") - 1);
Feature SwFeat = ((DrawingDoc)SwDoc).FeatureByName(BlockName);
SketchManager SwSktManager = SwDoc.SketchManager;
MathUtility swMathUtility = SwApp.GetMathUtility();
double[] xyz = new double[] { 1, 2, 3 };
MathPoint swMathPoint = swMathUtility.CreatePoint(xyz);
#region 全新插入
if (SwFeat == null)
{
SketchBlockDefinition SwBlockDefinition = SwSktManager.MakeSketchBlockFromFile(swMathPoint, BlockPath, false, 1, 0);
}
#endregion
#region 非全新插入--只要特征樹又特征担扑,就是非全新
else
{
SketchBlockDefinition SwBlockDefinition = SwFeat.GetSpecificFeature2();
SketchBlockInstance SwBlockIns = SwSktManager.InsertSketchBlockInstance(SwBlockDefinition, swMathPoint, 1, 0);
SwBlockIns.Name = "ABC"+ (SwBlockDefinition.GetInstanceCount()+1).ToString().Trim();
((FeatureManager)SwDoc.FeatureManager).UpdateFeatureTree();
}
#endregion
//一個塊定義的所有實(shí)例是聯(lián)動修改的
}
運(yùn)行效果
每個圖塊都是塊定義ABC的一個實(shí)例
實(shí)例3:獲取工程圖塊信息
遍歷工程圖中圖塊的信息
public static void GetBlockIns(ModelDoc2 SwDoc)
{
SketchManager SwSktManager = SwDoc.SketchManager;
object[] ObjBlockDefs = SwSktManager.GetSketchBlockDefinitions();
StringBuilder Sb = new StringBuilder("塊定義數(shù)量:" + ObjBlockDefs.Length.ToString().Trim() + "\r\n");
foreach (object ObjBlockDef in ObjBlockDefs)
{
SketchBlockDefinition SwBlockDef = (SketchBlockDefinition)ObjBlockDef;
Sb.Append("塊特征:"+SwBlockDef.GetFeature().Name+"\r\n");
Sb.Append("引用路徑:" + SwBlockDef.FileName+ "\r\n");
Sb.Append("引用數(shù)量:" + SwBlockDef.GetInstanceCount().ToString().Trim() + "\r\n");
if (SwBlockDef.GetInstanceCount() > 0)
{
Sb.Append("具體實(shí)例:\r\n");
object[] ObjInses = SwBlockDef.GetInstances();
foreach (object ObjIns in ObjInses)
{
SketchBlockInstance SwBlockIns = (SketchBlockInstance)ObjIns;
Sb.Append("實(shí)例名:" + SwBlockIns.Name + "\r\n");
}
}
Sb.Append("********************************\r\n");
}
System.Windows.Forms.MessageBox.Show(Sb.ToString().Trim());
}