SolidWorks插件----实体坐标系移动到原点

通过PropertyManagerPage操作界面来实现移动坐标系到原点

通过2步完成:1、平移;2、旋转;

SolidWorks提供了一个接口完成平移和旋转(InsertMoveCopyBody2),但是经过我这边测试发现这个接口有点问题,旋转的时候我们需要调换Z和X的位置;

现在我讲讲具体的实现过程:

1、获取需要移动的实体;

2、指定移动的坐标系;(PropertyManagerPageSelectionbox可以指定选择对象)

代码:(获取坐标系对象)

// 获取当前活动的文档
ModelDoc2 swModel = (ModelDoc2)iSwApp.ActiveDoc;

PartDoc swPart = (PartDoc)swModel;
FeatureManager swFeatMgr = (FeatureManager)swModel.FeatureManager;

//// 获取参考坐标对象
SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager;
CoordinateSystemFeatureData swCoordinateData = default(CoordinateSystemFeatureData);
for (int i = 1; i <= swSelMgr.GetSelectedObjectCount2(2); i++)
{
    if (swSelMgr.GetSelectedObjectType3(i, 2) == (int)swSelectType_e.swSelCOORDSYS)
    {
        Feature swTempFeat = (Feature)swSelMgr.GetSelectedObject6(i, 2);
        swCoordinateData = (CoordinateSystemFeatureData)swTempFeat.GetDefinition();
        break;
    }
}

坐标系对象不为空,我们来实现平移和旋转:

if (swCoordinateData != null)
{
	var transform = swCoordinateData.Transform;
	double[] vTransform = (double[])transform.ArrayData;

	// 第一步平移
	Feature swFeat1 = (Feature)swFeatMgr.InsertMoveCopyBody2(-vTransform[9], -vTransform[10],-vTransform[11], 
		0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, false, 1);

	// Get the bodies to move
	object[] bodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swAllBodies, false);
	SelectBodies(swModel, bodyArr);

	// 获取X,Y,Z旋转角
	double RotAngleX = 0.0, RotAngleY = 0.0, RotAngleZ = 0.0;
	double ThetaX = 0.0, ThetaY = 0.0, ThetaZ = 0.0;
	// 注意:旋转顺序为x y z,切记不能调换
	if (vTransform[2] < 1)
	{
		if (vTransform[2] > -1)
		{
			ThetaY = Math.Asin(vTransform[2]);
			ThetaX = Math.Atan2(-vTransform[5], vTransform[8]);
			ThetaZ = Math.Atan2(-vTransform[1], vTransform[0]);
		}
		else
		{
			ThetaY = -Math.PI / 2;
			ThetaX = -Math.Atan2(vTransform[3], vTransform[4]);
			ThetaZ = 0;
		}
	}
	else
	{
		ThetaY = Math.PI / 2;
		ThetaX = Math.Atan2(vTransform[3], vTransform[4]);
		ThetaZ = 0;
	}

	RotAngleX = ThetaX;
	RotAngleY = ThetaY;
	RotAngleZ = ThetaZ;

	// 第二步旋转
	Feature swFeat2 = (Feature)swFeatMgr.InsertMoveCopyBody2(0.0, 0.0,0.0,
	0.0, 0.0, 0.0, 0.0, RotAngleZ, RotAngleY, RotAngleX, false, 1);
}

public void SelectBodies(ModelDoc2 swModel, object[] bodyArr)
{
	// Select and mark the bodies to move
	SelectionMgr swSelMgr = default(SelectionMgr);
	SelectData swSelData = default(SelectData);
	Body2 swBody = default(Body2);
	bool status = false;
	int i = 0;

	swSelMgr = (SelectionMgr)swModel.SelectionManager;
	swSelData = (SelectData)swSelMgr.CreateSelectData();

	if ((bodyArr == null))
		return;
	for (i = 0; i <= bodyArr.GetUpperBound(0); i++)
	{

		swBody = (Body2)bodyArr[i];
		swSelData.Mark = 1;
		status = swBody.Select2(true, swSelData);
	}

}

 

你可能感兴趣的:(C#,SOLIDWORKS插件,C#知识)