C# SolidWorks二次开发—工程图中心标记(Center Marks)

C# SolidWorks二次开发—工程图中心标记(Center Marks)

工程图的中心标记

作为一个不专业的制图人员,我就不解释中心标记是什么了。大家自己看Solidworks的官方帮助说明(好像不应该放英文的,大家都看不懂了
)。


就是这么个东东。
我自己画了一个非常复杂的图纸,创建主视图的时候好像就自动增加了中心标记,蛮智能的。

不过上面的和我们今天在学习的没有什么关系,我们先看一下怎么删除这些中心标记,要用代码哈。
先找找api的内容:
找到了一个接口,里面就有例子。
但是看了下,它讲了,中心标记现在是annotations,以前是features.
所以针对不同的版本的solidworks可能是不同的对象。
当然我们是新版的,肯定是annotation了. 那其实就是遍历注释了,然后再判断是不是属于center mark


那下面开始干活.

一、遍历中心标记

		   //请先打开HolePlate.slddrw文件

            var swApp = PStandAlone.GetSolidWorks();

            var swModel = (ModelDoc2)swApp.ActiveDoc;

            var swDrawing = (DrawingDoc)swModel;

            //这里改成工程图中的视图名称

            swDrawing.ActivateView("Drawing View1");

            #region 遍历并删除
            //得到视图对象
            var swView = (View)swDrawing.ActiveDrawingView;

            //获取所有注释
            var annos = (object[])swView.GetAnnotations();

            //清空选择
            swModel.ClearSelection();

            //遍历中心标记
            foreach (var anno in annos)
            {
                var tempAnno = (Annotation)anno;
                if (tempAnno.GetType() == (int)swAnnotationType_e.swCenterMarkSym)
                {
                    //选中
                    tempAnno.Select(true);

                }

            }

            //删除选中
            swModel.EditDelete();
            #endregion

二、自动增加中心标记

增加的话非常简单,就一行代码,里面参数说明如下图:

         #region 自动增加
            //增加中心标记

            swView.AutoInsertCenterMarks2((int)swAutoInsertCenterMarkTypes_e.swAutoInsertCenterMarkType_Slots| (int)swAutoInsertCenterMarkTypes_e.swAutoInsertCenterMarkType_Hole , (int)swCenterMarkConnectionLine_e.swCenterMark_ShowLinearConnectLines, true, true, true, 0.0025, 0.0025, true, true, 0);

            #endregion

执行完所有的代码,结果如下图,因为我们参数里写了slot也增加中心标记,所以现在上面都有了。


总结

以上就是今天的所有内容了,最后再贴个漂亮的UI。

我又骗人了。

源码自取:
https://gitee.com/painezeng/CSharpAndSolidWorks

posted @
2022-09-21 20:00 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源

SolidWorks二次开发—装配体中打开零件时保持方向

SolidWorks二次开发—装配体中打开零件时保持方向

不出意外,这是8月份最后一篇博文了。
其实代码在gitee上提交了很久了,一直没写博文。
前一段时间,在solidworks看到了这个小图标,这个功能是在装配体界面上查看零件预览,它和单独打开零件时的区别在于,在这里预览的时候零件的方向和选中时一样。


零件单独打开时是这样的状态,这个状态是零件保存时的方向,和资源管理器上预览图标显示一致。

今天要做的功能,就是做个小功能,让零件单独打开的时候保持和装配体右侧预览的方向一样。
(大家可以自己想一想,要怎么实现。)

——————————————————-分—————–分———————————————————–

这样有某些特定情况下,会更方便确定我要修改的位置。

先大概说一下原理,就是在装配环境下先获取选中零件的变换矩阵,然后打开零件之后,把当前视角的矩阵变换为装配体相对的方向。
上代码:

 private void btnKeepView_Click(object sender, EventArgs e)
        {
            var swApp = PStandAlone.GetSolidWorks();

            var swModel = (ModelDoc2)swApp.ActiveDoc;                     

            var oldView = swApp.IActiveDoc2.IActiveView;

            var oldAsmOrientation = oldView.Orientation3; //矩阵向量
            var oldAsmsc = oldView.Scale2; //比例

            var swModelAsm = (AssemblyDoc)swModel; //获取当前零件
                                 
            var baseComp = swModel.ISelectionManager.GetSelectedObjectsComponent3(1, -1);

            var PartTransform2 = baseComp.Transform2;//零件与装配体坐标完全重合 变换到安装位置的变换
                           
            baseComp.Select(false);
            
            swModelAsm.OpenCompFile();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            var newView = swApp.IActiveDoc2.IActiveView;

            newView.Orientation3 = PartTransform2.IMultiply(oldAsmOrientation);
           
            //newView.Scale2 = oldAsmsc; 

            swModel.ViewZoomtofit();

            newView.GraphicsRedraw(null);

        }

代码很简单,但是解释起来也有点麻烦,因为我的数学也不好,我就不解释了,怕误导大家。


在装配中选中零件后,执行命令后,零件被打开,并自动切换和装配一样的相对视角。

好,就写这么多了。将就看吧。

posted @
2022-08-29 15:24 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源

C# SolidWorks二次开发—工程图简单版标注孔信息

C# SolidWorks二次开发—工程图简单版标注孔信息

突然感觉好久没有写技术文章了,确实,回头看了一下上次的文章,快一个月了。我在忙什么?

文章目录


目标

提示:今天的内容和上一篇属于一个范围,就是工程图的标注

其实代码已经完成好久了,只是没有发文章,今天来说一下孔信息标注的内容。


一、要标什么?

一般来说,工程图上的孔信息主要就是定位与大小,外加上公差 基准这些,但这有点复杂,我们从简,标X 方向 Y 方向 ,再标上孔大小,相同尺寸的合并一下前缀。

二、思路

与上篇类似就是找基准,找孔, 读信息,再标注。

感觉写了很多,但字却很少。 可能是觉得大家都已经学会了。

三、代码


代码有点多,反正我也讲不明白,就贴一下结果。

这样还是会有一些重叠问题,再调用一下自动整理尺寸的功能:

    private void btnAddDimForHoles_Click(object sender, EventArgs e)
        {
            var swApp = PStandAlone.GetSolidWorks();

            var swModel = (ModelDoc2)swApp.ActiveDoc;
            AddSizeDimensionForDrawing addSizeDimensionForDrawing = new AddSizeDimensionForDrawing(swApp, swModel);
            addSizeDimensionForDrawing.AutoAddHoleDimesnions("");
        }
    /// <summary>
    /// 给工程图标注长宽
    /// </summary>
    internal class AddSizeDimensionForDrawing
    {
        public SldWorks swApp { get; set; }
        public ModelDoc2 swModel  { get; set; }
        public SelectData swSelData { get; set; }
        public string  strError { get; set; }

        //public string Options = "Two";

        /// <summary>
        /// 尺寸标注上方
        /// </summary>
        public bool DimOnTop = true;

        /// <summary>
        /// 尺寸标注左侧
        /// </summary>
        public bool DimOnLeft = true;

        /// <summary>
        /// 尺寸位置偏移量
        /// </summary>
        public double HorOffset = 0.005;
        /// <summary>
        /// 尺寸位置偏移量
        /// </summary>
        public double VerOffset = 0.005;


        #region Holes相关
            
        /// <summary>
        /// 孔边集合
        /// </summary>
        List<Edge> swHoleList = new List<Edge>();

        /// <summary>
        /// 边集合
        /// </summary>
        List<Edge> swEdgesList = new List<Edge>();

        /// <summary>
        /// 点集合
        /// </summary>
        List<Vertex> swPointList = new List<Vertex>();



        #endregion


        public AddSizeDimensionForDrawing(SldWorks App, ModelDoc2 model)
        {

            swApp = App;
            swModel = model;

        }

        double AllowAutoArrange = 0;

        /// <summary>
        /// 自动增加孔尺寸
        /// </summary>
        /// <param name="s"></param>
        public void AutoAddHoleDimesnions(string s) {

 
            var swDraw = swModel as DrawingDoc;

            if (swDraw != null)
            {
                HorOffset = 0;
                VerOffset = 0;



                var swModelDocExt = (ModelDocExtension)swModel.Extension;
                var swSelMgr = (SelectionMgr)swModel.SelectionManager;


                swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true);


                //当前图纸
                Sheet swSheet = (Sheet)swDraw.GetCurrentSheet();
                //所有视图
                var swViews = (object[])swSheet.GetViews();

                swModel.ClearSelection2(true);
                //循环
                for (int i = 0; i < swViews.Length; i++)
                {

                    View swView = (View)swViews[i];

                    if (swView.GetOrientationName() != "*Isometric" && swView.GetOrientationName() != "*Trimetric" && swView.GetOrientationName() != "*Dimetric")
                    {
                        var vBounds = (double[])swView.GetOutline();

                        var swViewType = System.IO.Path.GetExtension(swView.GetReferencedModelName());

                        var vComps = (object[])swView.GetVisibleComponents();

                        if ( swView.GetVisibleComponentCount() > 0 )
                        {
                            var vEdges = (object[])swView.GetVisibleEntities((Component2)vComps[0], (int)swViewEntityType_e.swViewEntityType_Edge);
                            swSelData = (SelectData)swModel.ISelectionManager.CreateSelectData();
                            swSelData.View = swView;                         
                            MathTransform swViewXform = ViewMathTransform(swDraw, swView);
                            for (int itr = 0; itr < vEdges.Length; itr++)
                            {
                                var swCurve = (Curve)((Edge)vEdges[itr]).GetCurve();
                                if (swCurve.IsCircle()) {

                                    var swCircleParam = swCurve.GetEndParams(out double StartP, out double EndP, out bool IsClosedP, out bool IsPeriodicP);

                                    if (IsClosedP)
                                    {

                                        swHoleList.Add((Edge)vEdges[itr]);

                                    }

                                }

                                else {

                                    swEdgesList.Add((Edge)vEdges[itr]);
                                    var startVertex = ((Edge)vEdges[itr]).GetStartVertex();

                                    swPointList.Add((Vertex)startVertex);

                                }






                            }

                            Entity swEntXmax = null, swEntXmin = null, swEntYmax = null, swEntYmin =null;

                            var refModel = swView.ReferencedDocument;

                            if (swViewType.ToString().ToLower()==".sldprt")
                            {
                              
                                if (swPointList.Count>0)
                                {

                                    swEntXmax = FindExtremun(0, "max", swPointList, refModel.GetType(), swViewXform);
                                    swEntXmin = FindExtremun(0, "min", swPointList, refModel.GetType(), swViewXform);
                                    swEntYmax = FindExtremun(1, "max", swPointList, refModel.GetType(), swViewXform);
                                    swEntYmin = FindExtremun(1, "min", swPointList, refModel.GetType(), swViewXform);

                                }

                                if (swHoleList.Count>0)
                                {
                                    AllowAutoArrange = 0;
                                    HorOffset = HorOffset + 0.01;
                                    VerOffset = VerOffset + 0.001;
                                    var swHcollSortX = SortHoles(0, swHoleList, swViewType, "CleanYes", swViewXform);// ' 0 = X ,1 = Y
                                    PlaceHoleDimension((Vertex)swEntXmin , swHcollSortX, "Horizontal", vBounds, swViewType, swViewXform);
                                    var swHcollSortY = SortHoles(1, swHoleList, swViewType, "CleanYes", swViewXform);      // ' 0 = X ,1 = Y
                                    PlaceHoleDimension((Vertex)swEntYmax, swHcollSortY, "Vertical", vBounds, swViewType, swViewXform);
                                    PlaceHoleLocationDimension(swHoleList, vBounds, swViewType, swViewXform);


                                }

                                if (AllowAutoArrange > 0 && AllowAutoArrange< 0.005 )
                                {
                                   var swViewAnnot = (object[])swView.GetAnnotations();
                                    Annotation annotation;
                                    foreach (var item in swViewAnnot)
                                    {
                                        annotation = (Annotation)item;

                                        annotation.Select3(true, null);
                                    }


                                    swModelDocExt.AlignDimensions((int)swAlignDimensionType_e.swAlignDimensionType_AutoArrange, 0.001);

                                }


                            }



                        }



                    }



                }

            }
            swModel.ClearSelection2(true);
            swModel.GraphicsRedraw2();




        }

        /// <summary>
        /// 标注孔位置尺寸
        /// </summary>
        /// <param name="swHcoll"></param>
        /// <param name="vBounds"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        private void PlaceHoleLocationDimension(List<Edge> swHcoll, double[] vBounds, string swViewType, MathTransform swViewXform)
        {
            try
            {

                var swColl = new List<Edge>();
                var swTempColl = new List<Edge>();
                swColl.AddRange(swHcoll);

                for (int n = swColl.Count - 1; n >= 0; n--)
                {
                    swTempColl.Clear();

                    (swColl[n] as Entity).Select4(false, swSelData);
                    var swCircleCurve = (Curve)swColl[n].GetCurve();
                    var swCircleParams = (double[])swCircleCurve.CircleParams;
                    var swTempRadius = swCircleParams[6];
                    swTempColl.Add(swColl[n]);
                    swColl.Remove(swColl[n]);

                    for (int j = swColl.Count - 1; j >= 0; j--)
                    {
                        swCircleCurve = (Curve)swColl[j].GetCurve();
                        (swHcoll[j] as Entity).Select4(false, swSelData);

                        swCircleParams = (double[])swCircleCurve.CircleParams;

                        if (Math.Abs(swTempRadius-swCircleParams[6])<0.001) {
                            swTempColl.Add(swColl[j]);
                            swColl.Remove(swColl[j]);
                        }              
       

                    }

                    swTempColl = SortHoles(1, swTempColl, swViewType, "CleanNo", swViewXform);
                    swTempColl = SortHoles(0, swTempColl, swViewType, "CleanNo", swViewXform);

                    swCircleParams = CircleCoordinates(swTempColl[0], swViewType, swViewXform);

                    var Xpos = swCircleParams[0] - 0.025;
                   var  Ypos = vBounds[3];
                    (swTempColl[0] as Entity).Select4(false, swSelData);

                    var myDisplayDim = (DisplayDimension)swModel.AddDimension2(Xpos, Ypos, 0);
                    if (swTempColl.Count > 2)
                    {

                        myDisplayDim.SetBrokenLeader2(false, (int)swDisplayDimensionLeaderText_e.swBrokenLeaderHorizontalText);
                        var oldText = myDisplayDim.GetText((int)swDimensionTextParts_e.swDimensionTextPrefix);
                        myDisplayDim.SetText((int)swDimensionTextParts_e.swDimensionTextPrefix, $"{swTempColl.Count}x{oldText}");

                    }
                    n = swColl.Count;

            }



            }
            catch (Exception ex )
            {
                swApp.SendMsgToUser(ex.StackTrace);
                throw;
            }




        }

        /// <summary>
        /// 标注孔尺寸
        /// </summary>
        /// <param name="swVertex"></param>
        /// <param name="swHcoll"></param>
        /// <param name="DimOrientation"></param>
        /// <param name="vBounds"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        private void PlaceHoleDimension(Vertex swVertex, List<Edge> swHcoll, string DimOrientation, double[] vBounds, string swViewType, MathTransform swViewXform)
        {
            try
            {
      
               swModel.ClearSelection2(true);

                var vPt = PointCoordinates(swApp,swVertex, swViewType, swViewXform);
                var vPt2 = CircleCoordinates(swHcoll[0], swViewType, swViewXform);
                double Xpos, Ypos;

                (swVertex as Entity).Select4(true, swSelData);

                //double dblConvFactor = GetUnitConvFactor("");

                if (DimOrientation == "Horizontal")
                {
                    (swHcoll[0] as Entity).Select4(true, swSelData);
                    vPt2 = CircleCoordinates(swHcoll[0], swViewType, swViewXform);
                    Xpos = (vPt[0] + vPt2[0]) / 2;

                    Ypos = (vBounds[3] + HorOffset);

                    if (AllowAutoArrange == 0 || AllowAutoArrange > (Math.Abs(vPt[0] - vPt2[0]))) 
                    {

                        AllowAutoArrange = Math.Abs(vPt[0] - vPt2[0]);
                    }

                    var myDisplayDim = swModel.AddHorizontalDimension2(Xpos, Ypos, 0);

                }
                if (DimOrientation == "Vertical")
                {
                    (swHcoll[0] as Entity).Select4(true, swSelData);

                    vPt2 = CircleCoordinates(swHcoll[0], swViewType, swViewXform);
                    Xpos = (vBounds[0] - VerOffset);

                    Ypos = (vPt[1] + vPt2[1]) / 2; ;

                    if (AllowAutoArrange == 0 || AllowAutoArrange > (Math.Abs(vPt[1] - vPt2[1])))
                    {

                        AllowAutoArrange = Math.Abs(vPt[1] - vPt2[1]);
                    }

                    var myDisplayDim = swModel.AddVerticalDimension2(Xpos, Ypos, 0);

                }
                swModel.ClearSelection2(true);

                for (int i = 0; i < swHcoll.Count-1; i++)
                {
                    swModel.ClearSelection2(true);
                    (swHcoll[i+1] as Entity).Select4(true, swSelData);
                    var vPt1 = CircleCoordinates(swHcoll[i], swViewType, swViewXform);
                    vPt2 = CircleCoordinates(swHcoll[i + 1], swViewType, swViewXform);

                    if (DimOrientation == "Horizontal")
                    {
                        if (Math.Round(vPt1[1],10)!= Math.Round(vPt2[1], 10))
                        {
                            (swVertex as Entity).Select4(true, swSelData);
                            HorOffset = HorOffset + 0.005;
                            Xpos = (vPt[0] + vPt2[0]) / 2;
                            Ypos = (vBounds[3] + HorOffset);

                        }
                        else
                        {
                            (swHcoll[i] as Entity).Select4(true, swSelData);

                            Xpos = (vPt1[0] + vPt2[0]) / 2;
                            Ypos = (vBounds[3] + HorOffset);

                            if (AllowAutoArrange == 0 || AllowAutoArrange > (Math.Abs(vPt[0] - vPt2[0])))
                            {

                                AllowAutoArrange = Math.Abs(vPt[0] - vPt2[0]);
                            }
                        }
                        var myDisplayDim = swModel.AddHorizontalDimension2(Xpos, Ypos, 0);


                    }else  if (DimOrientation == "Vertical") {

                        (swHcoll[i] as Entity).Select4(true, swSelData);

                        //vPt2 = CircleCoordinates(swHcoll[0], swViewType, swViewXform);

                        Xpos = (vBounds[0] - VerOffset);

                        Ypos = (vPt[1] + vPt2[1]) / 2; ;

                        if (AllowAutoArrange == 0 || AllowAutoArrange > (Math.Abs(vPt[1] - vPt2[1])))
                        {

                            AllowAutoArrange = Math.Abs(vPt[1] - vPt2[1]);
                        }

                        var myDisplayDim = swModel.AddVerticalDimension2(Xpos, Ypos, 0);
                    }


                }



            }
            catch (Exception ex )
            {
                swApp.SendMsgToUser(ex.StackTrace.ToString());
                throw;
            }

        }

        /// <summary>
        /// 排序孔
        /// </summary>
        /// <param name="axis"></param>
        /// <param name="swHcoll"></param>
        /// <param name="swViewType"></param>
        /// <param name="swNeedToClean"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private List<Edge> SortHoles(int axis, List<Edge> swHcoll, string swViewType, string swNeedToClean, MathTransform swViewXform)
        {
            try
            {
                var swColl = new List<Edge>();
                swColl.AddRange(swHcoll);

                for (int i = 0; i < swColl.Count; i++)
                {

                    for (int j = 0; j < swColl.Count-i-1; j++)
                    {
                       double[] swCircleParams1 = CircleCoordinates(swColl[j], swViewType, swViewXform);
                       double[] swCircleParams2 = CircleCoordinates(swColl[j+1], swViewType, swViewXform);
                        if (axis==0)
                        {
                            if (swCircleParams1[axis]>swCircleParams2[axis])
                            {
                                var vTemp = swColl[j + 1];
                                swColl.Remove(swColl[j + 1]);
                                swColl.Insert(j, vTemp);
                            }


                        }
                        else if (axis==1)
                        {
                            if (swCircleParams1[axis] < swCircleParams2[axis])
                            {
                                var vTemp = swColl[j + 1];
                                swColl.Remove(swColl[j + 1]);
                                swColl.Insert(j, vTemp);
                            }

                        }
                    }      
                }

                if (swNeedToClean== "CleanYes")
                {
                    return CleanSortedHoles(axis, swColl, swViewType, swViewXform);

                }
                else if (swNeedToClean == "CleanNo")
                {
                    return swColl;
                }


                return null;
            }
            catch (Exception ex )
            {
                swApp.SendMsgToUser(ex.StackTrace);
                return null;
            }



         
        }

        /// <summary>
        /// 清理排序过的孔,比如X值 一样, Y值 一样的
        /// </summary>
        /// <param name="axis"></param>
        /// <param name="swColl"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private List<Edge> CleanSortedHoles(int axis, List<Edge> swColl, string swViewType, MathTransform swViewXform)
        {
            try
            {
                for (int k = 0; k < swColl.Count-2; k++)
                {

                    for (int n = swColl.Count - 1; n >= 1; n--)
                    {
                        double[] swCircleParams1 = CircleCoordinates(swColl[n], swViewType, swViewXform);
                        double[] swCircleParams2 = CircleCoordinates(swColl[n - 1], swViewType, swViewXform);

                        if (Math.Abs(swCircleParams1[axis]- swCircleParams2[axis])<0.000001)
                        {


                            if (axis == 0)
                            {
                                if (swCircleParams1[Math.Abs(axis-1)] > swCircleParams2[Math.Abs(axis - 1)])
                                {
                                   
                                    swColl.Remove(swColl[n - 1]);
                        
                                }
                                else
                                {
                                    swColl.Remove(swColl[n]);
                                }


                            }
                            else if (axis == 1)
                            {
                                if (swCircleParams1[Math.Abs(axis - 1)] < swCircleParams2[Math.Abs(axis - 1)])
                                {

                                    swColl.Remove(swColl[n - 1]);

                                }
                                else
                                {
                                    swColl.Remove(swColl[n]);
                                }
                            }

                        }


                    }
                }


                return swColl;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 圆点坐标
        /// </summary>
        /// <param name="swCircle"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private double[] CircleCoordinates(Edge swCircle, string swViewType, MathTransform swViewXform)
        {

            Curve swCircleCurve = (Curve)swCircle.GetCurve();
            var swCircleParams = (double[])swCircleCurve.CircleParams;
            var vPt = new double[3];
            vPt[0] = swCircleParams[0];
            vPt[1] = swCircleParams[1];
            vPt[2] = swCircleParams[2];

            var swMathUtils =(MathUtility) swApp.GetMathUtility();
            var swMathPt = (MathPoint)swMathUtils.CreatePoint(vPt);
            var swComp =(Component2) (swCircle as Entity).GetComponent();

            if (swViewType.ToUpper()==".SLDASM")
            {
                var swCompXform = swComp.Transform2;
                var swTotalXForm = swCompXform.Multiply(swViewXform);
                swMathPt = (MathPoint)swMathPt.MultiplyTransform(swTotalXForm);
            }
            else
            {
                swMathPt = (MathPoint)swMathPt.MultiplyTransform(swViewXform);
            }
            return (double[])swMathPt.ArrayData;

        }


        /// <summary>
        /// 增加长宽尺寸
        /// </summary>
        /// <param name="Top">尺寸位置放左?</param>
        /// <param name="Left">尺寸位置放右?</param>
        public void AutoAddSize(bool Top = true, bool Left = true) {

            try
            {
                DimOnLeft = Left;
                DimOnTop = Top;
                AutoOveralDimensions();
            }
            catch (Exception)
            {

                throw;
            }       
        
        
        }

        /// <summary>
        /// 标注
        /// </summary>
        public void AutoOveralDimensions() {
                     

            var swDraw = swModel as DrawingDoc;

            if (swDraw != null) 
            {
                //当前图纸
                Sheet swSheet = (Sheet)swDraw.GetCurrentSheet();
                //所有视图
                var swViews = (object[])swSheet.GetViews();

                //循环
                for (int i = 0; i < swViews.Length; i++) {

                    View swView = (View)swViews[i];
                    //可以排除关联视图
                    if (swView.Type==(int)swDrawingViewTypes_e.swDrawingNamedView)
                    {
                        if (swView.GetOrientationName() != "*Isometric" && swView.GetOrientationName() != "*Trimetric" && swView.GetOrientationName() != "*Dimetric")
                        {

                            ProcessView(swDraw, swView, true, true);

                            //找关联视图
                            var depHorView = GetAlignedDependantView(swView, 0);

                            if (depHorView != null)
                            {
                                ProcessView(swDraw, depHorView, true, false);
                            }
                            var depVerView = GetAlignedDependantView(swView, 1);

                            if (depVerView != null)
                            {
                                ProcessView(swDraw, depVerView, false, true);
                            }
                        }

                    }


                }

            }
            swModel.ClearSelection2(true);
            swModel.GraphicsRedraw2();

        }

        /// <summary>
        /// 找关联视图
        /// </summary>
        /// <param name="swParentView"></param>
        /// <param name="intOrientation">方向,横向/纵向</param>
        /// <returns></returns>
        private View GetAlignedDependantView(View swParentView, int intOrientation)
        {
            var delta = 0.00001;

            var intDependantViews = swParentView.GetDependentViewCount(false, (int)swDrawingViewTypes_e.swDrawingProjectedView);
            var objDependantViews = (object[])swParentView.GetDependentViews(false, (int)swDrawingViewTypes_e.swDrawingProjectedView);

            var ParentPos =(double[]) swParentView.Position;

            for (int i = 0; i < intDependantViews; i++)
            {
                var depView = (View)objDependantViews[i];

                var DependantPos = (double[])depView.Position;

                if (Math.Abs(ParentPos[Math.Abs(intOrientation - 1)] - DependantPos[Math.Abs(intOrientation - 1)])<delta) {

                    return depView;

                }
            }

           return null;
        }


       /// <summary>
       /// 遍历 点 ,计算再标注
       /// </summary>
       /// <param name="swDraw"></param>
       /// <param name="swView"></param>
       /// <param name="PlaceHorDim"></param>
       /// <param name="PlaceVerDim"></param>
        private void ProcessView(DrawingDoc swDraw, View swView, bool PlaceHorDim, bool PlaceVerDim)
        {

            List<Vertex> swPcoll= new List<Vertex> ();

            swModel.ClearSelection2(true);

            var refModel= swView.ReferencedDocument;

            var vComps = (object[])swView.GetVisibleComponents();

            MathTransform swViewXform = ViewMathTransform(swDraw, swView);

            //获取所有直线边点
            for (int j = 0;j < swView.GetVisibleComponentCount(); j++)
            {
                var vEdges = (object[])swView.GetVisibleEntities((Component2)vComps[j], (int)swViewEntityType_e.swViewEntityType_Edge);
                  swSelData = (SelectData)swModel.ISelectionManager.CreateSelectData();
                    for (int itr = 0; itr < vEdges.Length; itr++)
                    {
                        var swCurve = (Curve)((Edge)vEdges[itr]).GetCurve();
                        if (!swCurve.IsCircle())
                        {
                            var startVertex= (Vertex)((Edge)vEdges[itr]).GetStartVertex();
                            var endVertex = (Vertex)((Edge)vEdges[itr]).GetEndVertex();

                            if (startVertex !=null)
                            {
                                swPcoll.Add(startVertex);
                            }
                            if (endVertex != null)
                            {
                                swPcoll.Add(endVertex);
                            }
                        }

                    }
            }

            Entity swEntXmax, swEntXmin, swEntYmax, swEntYmin;


            if (swPcoll.Count>0)
            {

                swEntXmax = FindExtremun(0, "max", swPcoll, refModel.GetType(), swViewXform);
                swEntXmin = FindExtremun(0, "min", swPcoll, refModel.GetType(), swViewXform);
                swEntYmax = FindExtremun(1, "max", swPcoll, refModel.GetType(), swViewXform);
                swEntYmin = FindExtremun(1, "min", swPcoll, refModel.GetType(), swViewXform);


                var vBounds = (double[])swView.GetOutline();

                if (PlaceHorDim)
                {
                    PlaceOverallDimension(swModel, swEntXmax, swEntXmin, "Horizontal", vBounds);
                }

                if (PlaceVerDim)
                {
                    PlaceOverallDimension(swModel, swEntYmax, swEntYmin, "Vertical", vBounds);
                }

            }

        }
        /// <summary>
        /// 放置尺寸
        /// </summary>
        /// <param name="swModel"></param>
        /// <param name="swVertex1"></param>
        /// <param name="swVertex2"></param>
        /// <param name="DimOrientation"></param>
        /// <param name="vBounds"></param>
        private void PlaceOverallDimension(ModelDoc2 swModel, Entity swVertex1, Entity swVertex2, string DimOrientation, double[] vBounds)
        {
            double dblConvFactor = GetUnitConvFactor("");
            if (DimOrientation == "Horizontal") {

                HorOffset = HorOffset * dblConvFactor;

            }
            if (DimOrientation == "Vertical")
            {
                VerOffset = VerOffset * dblConvFactor;
            }
            swModel.ClearSelection2(true);

            swVertex1.Select4(false, swSelData);
            swVertex2.Select4(true, swSelData);
            double Xpos, Ypos;

            if (DimOrientation == "Horizontal")
            {
                Xpos = (vBounds[0] + vBounds[2]) / 2;

                if(DimOnTop) //标注在顶部
                {
                    Ypos = (vBounds[3] + HorOffset);
                }
                else
                {
                    Ypos = (vBounds[1] - HorOffset);
                }

                var myDisplayDim = swModel.AddHorizontalDimension2(Xpos, Ypos, 0);


            } else if (DimOrientation == "Vertical")
            {
                Ypos = (vBounds[1] + vBounds[3]) / 2;

                if (DimOnLeft) 
                {
                    Xpos = (vBounds[0] - HorOffset);
                }
                else
                {
                    Xpos = (vBounds[2] + HorOffset);
                }

                var myDisplayDim = swModel.AddVerticalDimension2(Xpos, Ypos, 0);


            }


        }



        /// <summary>
        /// 获取单位
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private double GetUnitConvFactor(string v)
        {
            var LenUnit = swModel.GetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swUnitsLinear);
            switch (LenUnit)
            {
                case 0  : return 0.001;
                case 1  : return 0.01;
                case 2  : return 1;
                case 3  : return 0.0254;
                case 4  : return 0.3048;
                case 5  : return -1;
                case 6  : return 0.0000000001;
                case 7  : return 0.000000001;
                case 8  : return 0.000001;
                case 9  : return 0.00254;
                case 10  : return 0.00000254;
                default:
                    return -1;
                
            }         


        }

        /// <summary>
        /// 找极点
        /// </summary>
        /// <param name="axis"></param>
        /// <param name="MinMax"></param>
        /// <param name="swPcoll"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private Entity FindExtremun(int axis, string MinMax, List<Vertex> swPcoll, int swViewType, MathTransform swViewXform)
        {
            var swVertex = swPcoll[0];
            var vPt = PointCoordinates(swVertex, swViewType, swViewXform);
            var Extr = vPt[axis];

            for (int i = 0; i < swPcoll.Count; i++)
            {
                vPt = PointCoordinates(swPcoll[i], swViewType, swViewXform);

                if (MinMax=="max" && vPt[axis]>Extr)
                {
                    Extr = vPt[axis];
                    swVertex = swPcoll[i];

                }
                else if (MinMax == "min" && vPt[axis] < Extr)
                {
                    Extr = vPt[axis];
                    swVertex = swPcoll[i];

                }

            }
            return swVertex as Entity;

      
        }

        /// <summary>
        /// 坐标系转换
        /// </summary>
        /// <param name="swVertex"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private double[] PointCoordinates(Vertex swVertex, int swViewType, MathTransform swViewXform)
        {
            var swMathUtils = swApp.IGetMathUtility();
            var vPt = (double[])swVertex.GetPoint();
            var swMathPt = (MathPoint)swMathUtils.CreatePoint(vPt);

            if (swViewType==(int)swDocumentTypes_e.swDocASSEMBLY)
            {
                var swComp =(Component2) (swVertex as Entity).GetComponent();

                if (swComp!=null)
                {
                    MathTransform swCompXform = swComp.Transform2;

                    MathTransform swTotalXForm = (MathTransform)swCompXform.Multiply(swViewXform);

                     swMathPt = (MathPoint)swMathPt.MultiplyTransform(swTotalXForm);

                }

            }
            else
            {
                swMathPt = (MathPoint)swMathPt.MultiplyTransform(swViewXform);
            }

            return (double[])swMathPt.ArrayData;


        }

        /// <summary>
        /// 坐标系转换
        /// </summary>
        /// <param name="swVertex"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private double[] PointCoordinates(SldWorks swApp,Vertex swVertex, string swViewType, MathTransform swViewXform)
        {
            var swMathUtils = swApp.IGetMathUtility();
            var vPt = (double[])swVertex.GetPoint();
            var swMathPt = (MathPoint)swMathUtils.CreatePoint(vPt);

            if (swViewType == "SLDASM")
            {
                var swComp = (Component2)(swVertex as Entity).GetComponent();

                if (swComp != null)
                {
                    MathTransform swCompXform = swComp.Transform2;

                    MathTransform swTotalXForm = (MathTransform)swCompXform.Multiply(swViewXform);

                    swMathPt = (MathPoint)swMathPt.MultiplyTransform(swTotalXForm);

                }

            }
            else
            {
                swMathPt = (MathPoint)swMathPt.MultiplyTransform(swViewXform);
            }

            return (double[])swMathPt.ArrayData;


        }



        /// <summary>
        /// 视图转换
        /// </summary>
        /// <param name="swDraw"></param>
        /// <param name="swView"></param>
        /// <returns></returns>
        private MathTransform ViewMathTransform(DrawingDoc swDraw, View swView)
        {
            try
            {
                var swViewXform = (MathTransform)swView.ModelToViewTransform;
                var swSheet = (Sheet)swDraw.GetCurrentSheet();
                var swSheetView = (View)swDraw.GetFirstView();
                var swSheetXform = (MathTransform)swSheetView.ModelToViewTransform;

                var vSheetPrps = (double[])swSheet.GetProperties();
                var scaleNom = vSheetPrps[2];
                var scaleDenom = vSheetPrps[3];
                var ViewMatrix = (Double[])swSheetXform.ArrayData;
                ViewMatrix[12] = 1; //'scaleNom / scaleDenom
                var swMathUtil = (MathUtility)swApp.GetMathUtility();
                swSheetXform = (MathTransform)swMathUtil.CreateTransform(ViewMatrix);
                return (MathTransform)swViewXform.Multiply(swSheetXform.Inverse());

            }
            catch (Exception)
            {

                return null;
            }
        }






    }


总结

我这功能是抄来的,有问题别问我,哈哈

想要源码的自取

posted @
2022-08-02 19:15 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源

C# SolidWorks二次开发—工程图简单版标注长宽

C# SolidWorks二次开发—工程图简单版标注长宽

文章目录


工程图中标注长宽

工程图中标注常用方法有哪些?请思考再继续查看。

一、开发目标

在常规矩形零件的工程图中标注最大外形尺寸用于下料(此次不考虑圆形,因为我也不会。)

二、方案解析

1.思路










开始 遍历视图 遍历所有可见体 遍历可见线 排序点得到长宽 标注长宽 找对应投影视图 视图投影视图 视图投影视图中标注 下一视图 结束

2.关键代码

代码如下(示例):

namespace CSharpAndSolidWorks
{
    /// <summary>
    /// 给工程图标注长宽
    /// </summary>
    internal class AddSizeDimensionForDrawing
    {
        public SldWorks swApp { get; set; }
        public ModelDoc2 swModel  { get; set; }
        public SelectData swSelData { get; set; }
        public string  strError { get; set; }

        //public string Options = "Two";

        /// <summary>
        /// 尺寸标注上方
        /// </summary>
        public bool DimOnTop = true;

        /// <summary>
        /// 尺寸标注左侧
        /// </summary>
        public bool DimOnLeft = true;

        /// <summary>
        /// 尺寸位置偏移量
        /// </summary>
        public double HorOffset = 0.005;
        /// <summary>
        /// 尺寸位置偏移量
        /// </summary>
        public double VerOffset = 0.005;


        public AddSizeDimensionForDrawing(SldWorks App, ModelDoc2 model)
        {

            swApp = App;
            swModel = model;

        }

        /// <summary>
        /// 增加长宽尺寸
        /// </summary>
        /// <param name="Top">尺寸位置放左?</param>
        /// <param name="Left">尺寸位置放右?</param>
        public void AutoAddSize(bool Top = true, bool Left = true) {

            try
            {
                DimOnLeft = Left;
                DimOnTop = Top;
                AutoOveralDimensions();
            }
            catch (Exception)
            {

                throw;
            }       
        
        
        }

        /// <summary>
        /// 标注
        /// </summary>
        public void AutoOveralDimensions() {
                     

            var swDraw = swModel as DrawingDoc;

            if (swDraw != null) 
            {
                //当前图纸
                Sheet swSheet = (Sheet)swDraw.GetCurrentSheet();
                //所有视图
                var swViews = (object[])swSheet.GetViews();

                //循环
                for (int i = 0; i < swViews.Length; i++) {

                    View swView = (View)swViews[i];
                    //可以排除关联视图
                    if (swView.Type==(int)swDrawingViewTypes_e.swDrawingNamedView)
                    {
                        if (swView.GetOrientationName() != "*Isometric" && swView.GetOrientationName() != "*Trimetric" && swView.GetOrientationName() != "*Dimetric")
                        {

                            ProcessView(swDraw, swView, true, true);

                            //找关联视图
                            var depHorView = GetAlignedDependantView(swView, 0);

                            if (depHorView != null)
                            {
                                ProcessView(swDraw, depHorView, true, false);
                            }
                            var depVerView = GetAlignedDependantView(swView, 1);

                            if (depVerView != null)
                            {
                                ProcessView(swDraw, depVerView, false, true);
                            }
                        }

                    }


                }

            }
            swModel.ClearSelection2(true);
            swModel.GraphicsRedraw2();

        }

        /// <summary>
        /// 找关联视图
        /// </summary>
        /// <param name="swParentView"></param>
        /// <param name="intOrientation">方向,横向/纵向</param>
        /// <returns></returns>
        private View GetAlignedDependantView(View swParentView, int intOrientation)
        {
            var delta = 0.00001;

            var intDependantViews = swParentView.GetDependentViewCount(false, (int)swDrawingViewTypes_e.swDrawingProjectedView);
            var objDependantViews = (object[])swParentView.GetDependentViews(false, (int)swDrawingViewTypes_e.swDrawingProjectedView);

            var ParentPos =(double[]) swParentView.Position;

            for (int i = 0; i < intDependantViews; i++)
            {
                var depView = (View)objDependantViews[i];

                var DependantPos = (double[])depView.Position;

                if (Math.Abs(ParentPos[Math.Abs(intOrientation - 1)] - DependantPos[Math.Abs(intOrientation - 1)])<delta) {

                    return depView;

                }
            }

           return null;
        }


       /// <summary>
       /// 遍历 点 ,计算再标注
       /// </summary>
       /// <param name="swDraw"></param>
       /// <param name="swView"></param>
       /// <param name="PlaceHorDim"></param>
       /// <param name="PlaceVerDim"></param>
        private void ProcessView(DrawingDoc swDraw, View swView, bool PlaceHorDim, bool PlaceVerDim)
        {

            List<Vertex> swPcoll= new List<Vertex> ();

            swModel.ClearSelection2(true);

            var refModel= swView.ReferencedDocument;

            var vComps = (object[])swView.GetVisibleComponents();

            MathTransform swViewXform = ViewMathTransform(swDraw, swView);

            //获取所有直线边点
            for (int j = 0;j < swView.GetVisibleComponentCount(); j++)
            {
                var vEdges = (object[])swView.GetVisibleEntities((Component2)vComps[j], (int)swViewEntityType_e.swViewEntityType_Edge);
                  swSelData = (SelectData)swModel.ISelectionManager.CreateSelectData();
                    for (int itr = 0; itr < vEdges.Length; itr++)
                    {
                        var swCurve = (Curve)((Edge)vEdges[itr]).GetCurve();
                        if (!swCurve.IsCircle())
                        {
                            var startVertex= (Vertex)((Edge)vEdges[itr]).GetStartVertex();
                            var endVertex = (Vertex)((Edge)vEdges[itr]).GetEndVertex();

                            if (startVertex !=null)
                            {
                                swPcoll.Add(startVertex);
                            }
                            if (endVertex != null)
                            {
                                swPcoll.Add(endVertex);
                            }
                        }

                    }
            }

            Entity swEntXmax, swEntXmin, swEntYmax, swEntYmin;


            if (swPcoll.Count>0)
            {

                swEntXmax = FindExtremun(0, "max", swPcoll, refModel.GetType(), swViewXform);
                swEntXmin = FindExtremun(0, "min", swPcoll, refModel.GetType(), swViewXform);
                swEntYmax = FindExtremun(1, "max", swPcoll, refModel.GetType(), swViewXform);
                swEntYmin = FindExtremun(1, "min", swPcoll, refModel.GetType(), swViewXform);


                var vBounds = (double[])swView.GetOutline();

                if (PlaceHorDim)
                {
                    PlaceOverallDimension(swModel, swEntXmax, swEntXmin, "Horizontal", vBounds);
                }

                if (PlaceVerDim)
                {
                    PlaceOverallDimension(swModel, swEntYmax, swEntYmin, "Vertical", vBounds);
                }

            }

        }
        /// <summary>
        /// 放置尺寸
        /// </summary>
        /// <param name="swModel"></param>
        /// <param name="swVertex1"></param>
        /// <param name="swVertex2"></param>
        /// <param name="DimOrientation"></param>
        /// <param name="vBounds"></param>
        private void PlaceOverallDimension(ModelDoc2 swModel, Entity swVertex1, Entity swVertex2, string DimOrientation, double[] vBounds)
        {
            double dblConvFactor = GetUnitConvFactor("");
            if (DimOrientation == "Horizontal") {

                HorOffset = HorOffset * dblConvFactor;

            }
            if (DimOrientation == "Vertical")
            {
                VerOffset = VerOffset * dblConvFactor;
            }
            swModel.ClearSelection2(true);

            swVertex1.Select4(false, swSelData);
            swVertex2.Select4(true, swSelData);
            double Xpos, Ypos;

            if (DimOrientation == "Horizontal")
            {
                Xpos = (vBounds[0] + vBounds[2]) / 2;

                if(DimOnTop) //标注在顶部
                {
                    Ypos = (vBounds[3] + HorOffset);
                }
                else
                {
                    Ypos = (vBounds[1] - HorOffset);
                }

                var myDisplayDim = swModel.AddHorizontalDimension2(Xpos, Ypos, 0);


            } else if (DimOrientation == "Vertical")
            {
                Ypos = (vBounds[1] + vBounds[3]) / 2;

                if (DimOnLeft) 
                {
                    Xpos = (vBounds[0] - HorOffset);
                }
                else
                {
                    Xpos = (vBounds[2] + HorOffset);
                }

                var myDisplayDim = swModel.AddVerticalDimension2(Xpos, Ypos, 0);


            }


        }



        /// <summary>
        /// 获取单位
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private double GetUnitConvFactor(string v)
        {
            var LenUnit = swModel.GetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swUnitsLinear);
            switch (LenUnit)
            {
                case 0  : return 0.001;
                case 1  : return 0.01;
                case 2  : return 1;
                case 3  : return 0.0254;
                case 4  : return 0.3048;
                case 5  : return -1;
                case 6  : return 0.0000000001;
                case 7  : return 0.000000001;
                case 8  : return 0.000001;
                case 9  : return 0.00254;
                case 10  : return 0.00000254;
                default:
                    return -1;
                
            }         


        }

        /// <summary>
        /// 找极点
        /// </summary>
        /// <param name="axis"></param>
        /// <param name="MinMax"></param>
        /// <param name="swPcoll"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private Entity FindExtremun(int axis, string MinMax, List<Vertex> swPcoll, int swViewType, MathTransform swViewXform)
        {
            var swVertex = swPcoll[0];
            var vPt = PointCoordinates(swVertex, swViewType, swViewXform);
            var Extr = vPt[axis];

            for (int i = 0; i < swPcoll.Count; i++)
            {
                vPt = PointCoordinates(swPcoll[i], swViewType, swViewXform);

                if (MinMax=="max" && vPt[axis]>Extr)
                {
                    Extr = vPt[axis];
                    swVertex = swPcoll[i];

                }
                else if (MinMax == "min" && vPt[axis] < Extr)
                {
                    Extr = vPt[axis];
                    swVertex = swPcoll[i];

                }

            }
            return swVertex as Entity;

      
        }

        /// <summary>
        /// 坐标系转换
        /// </summary>
        /// <param name="swVertex"></param>
        /// <param name="swViewType"></param>
        /// <param name="swViewXform"></param>
        /// <returns></returns>
        private double[] PointCoordinates(Vertex swVertex, int swViewType, MathTransform swViewXform)
        {
            var swMathUtils = swApp.IGetMathUtility();
            var vPt = (double[])swVertex.GetPoint();
            var swMathPt = (MathPoint)swMathUtils.CreatePoint(vPt);

            if (swViewType==(int)swDocumentTypes_e.swDocASSEMBLY)
            {
                var swComp =(Component2) (swVertex as Entity).GetComponent();

                if (swComp!=null)
                {
                    MathTransform swCompXform = swComp.Transform2;

                    MathTransform swTotalXForm = (MathTransform)swCompXform.Multiply(swViewXform);

                     swMathPt = (MathPoint)swMathPt.MultiplyTransform(swTotalXForm);

                }

            }
            else
            {
                swMathPt = (MathPoint)swMathPt.MultiplyTransform(swViewXform);
            }

            return (double[])swMathPt.ArrayData;


        }
        /// <summary>
        /// 视图转换
        /// </summary>
        /// <param name="swDraw"></param>
        /// <param name="swView"></param>
        /// <returns></returns>
        private MathTransform ViewMathTransform(DrawingDoc swDraw, View swView)
        {
            try
            {
                var swViewXform = (MathTransform)swView.ModelToViewTransform;
                var swSheet = (Sheet)swDraw.GetCurrentSheet();
                var swSheetView = (View)swDraw.GetFirstView();
                var swSheetXform = (MathTransform)swSheetView.ModelToViewTransform;

                var vSheetPrps = (double[])swSheet.GetProperties();
                var scaleNom = vSheetPrps[2];
                var scaleDenom = vSheetPrps[3];
                var ViewMatrix = (Double[])swSheetXform.ArrayData;
                ViewMatrix[12] = 1; //'scaleNom / scaleDenom
                var swMathUtil = (MathUtility)swApp.GetMathUtility();
                swSheetXform = (MathTransform)swMathUtil.CreateTransform(ViewMatrix);
                return (MathTransform)swViewXform.Multiply(swSheetXform.Inverse());

            }
            catch (Exception)
            {

                return null;
            }
        }






    }
}


3.调用

            var swApp = PStandAlone.GetSolidWorks();

            var swModel = (ModelDoc2)swApp.ActiveDoc;

            AddSizeDimensionForDrawing addSizeDimensionForDrawing = new AddSizeDimensionForDrawing(swApp, swModel);
            addSizeDimensionForDrawing.AutoAddSize(false,false);


总结

今天代码有点多,也仅仅是针对规则的体进行处理,要达到生产可用状态还是有很路要走的,这里就靠大家发挥了。
比如: 圆如何处理,不规则体又如何处理,如何处理重复尺寸,如何进行尺寸位置的避让或者自动整理?这些问题待大家研究。

posted @
2022-07-05 10:59 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源

C# SolidWorks二次开发—获取和创建DimXpert(MBD)尺寸

C# SolidWorks二次开发—获取和创建DimXpert(MBD)尺寸

这里写自定义目录标题

MBD

MBD 代表 Model Based Definition(基于模型的定义),这是一种使用 3D 模型(如实体模型)、产品和制造信息 (PMI) 以及相关元数据来定义单个部件和产品装配体的方法。相比之下,传统上的其他方法都需要使用 2D 工程图来提供此类细节。

示例图

我找了一张图,这是PTC网站上的,我觉得看着不错。

我的解释

就是把常规的2d工程图甩掉,在模型上定义加工尺寸与信息。因为复杂的2d图需要你有丰富的3维构造想向力。而基于三维的话,更直观,还能动态旋转,想怎么看就怎么看。

本文章的目标

通过代码来自动创建3d尺寸标注,以及读取标注。

模型实现步骤

先建一个简单的模型,这里我们采用mbd提供的模板

就这样吧,太复杂 了怕我自己看不懂。

然后采用SolidWorks中的自动尺寸方案,然后出来的效果图(尺寸位置有手动整理)


整体效果还不错,我是选择了左下角的两个面为基准。(当然也发现六边形的孔它不标,可能要手动再增加)

选中某个尺寸,会自动高亮有对应的实体面。
像这个有两个对象,还会自动在前面2x

大家可能发现,尺寸有两种颜色 100和200是我在草图中有标注过的尺寸,它是黑色,而且没有公差。
其它出来的尺寸是自动公差的,这个值 是和前面选择的模型模板属于哪个尺寸级别有关的。公差带范围不一样。

如何修改公差

手动改:

文档属性里面可以控制默认值(这个值 改了之后 再增加的尺寸才会使用设置中的默认值) :

如何读取:

那肯定是查Api帮助。

这个示意是遍历了所有的尺寸特征(大家可以自己去试试,我就不贴了)
我就做个简单的(主要是复杂的我也不会)

执行这个按钮之前,我选中了这个尺寸。

private void btnCreateDimXpert_Click(object sender, EventArgs e)
        {

            var swApp = PStandAlone.GetSolidWorks();

            var swModel = (ModelDoc2)swApp.ActiveDoc;       

            var selectedObject = (object)swModel.ISelectionManager.GetSelectedObject6( 1, -1);

            var dimXpertFeature = selectedObject as DimXpertFeature;                   

            var dimType = dimXpertFeature.Type;

            var dimAnnotations = (object[])dimXpertFeature.GetAppliedAnnotations();

            for (int i = 0; i < dimAnnotations.Length; i++)
            {
                var tempAnno = (DimXpertAnnotation)dimAnnotations[i];

                var dimTol = (DimXpertDimensionTolerance)tempAnno;              

                MessageBox.Show(dimTol.GetNominalValue().ToString());
            }
        }

它居然给了提示了四个尺寸值 。
这样说明了一个问题,它设计的时候是针对 一个整体,这个特征上有四个尺寸来定义。
如果你想获取具体的公差值信息,可以参考Api帮助中的获取公差示例https://help.solidworks.com/2018/english/api/swdocmgrapi/get_dimxpert_tolerance5_example_csharp.htm

如何创建这些尺寸


通过查找 ,找到一个自动尺寸方案的示例。 这个示例我就不说了。因为我也看不懂,哈哈
https://help.solidworks.com/2018/english/api/swdimxpertapi/auto_dimension_scheme_example_csharp.htm

我就弄个简单的版本。
利用神器宏录制器,录制一个。

然后改成C#版本

   //先打开 MBDTest_Clear.SLDPRT
            #region C#转换版
            var boolstatus = swModel.Extension.SelectByRay(-0.199999999999932, 7.99159865590582E-03, 2.08147507191825E-03, 0.388737791327055, 0.42257073135628, -0.81872883581512, 1.1566601033182E-03, 2, false, 0, 0);
            boolstatus =swModel.Extension.SelectByRay(-0.193540180170828, 0, 7.74886573458389E-03, 0.388737791327055, 0.42257073135628, -0.81872883581512, 1.1566601033182E-03, 2, true, 0, 0);
            boolstatus =swModel.Extension.SelectByRay(-8.93087496499163E-02, 7.75246027125149E-02, 6.27227943436992E-03, 0.388737791327055, 0.42257073135628, -0.81872883581512, 1.1566601033182E-03, 2, true, 0, 0);
            boolstatus =swModel.ISelectionManager.SetSelectedObjectMark(3, 51,(int)swSelectionMarkAction_e.swSelectionMarkSet);
            boolstatus =swModel.Extension.SelectByRay(-0.117784661174085, 3.60124267366473E-02, 4.68486280385605E-03, 0.388737791327055, 0.42257073135628, -0.81872883581512, 1.1566601033182E-03, 2, true, 0, 0);
            boolstatus =swModel.ISelectionManager.SetSelectedObjectMark(4, 52, (int)swSelectionMarkAction_e.swSelectionMarkSet);
            var swConfig = swModel.ConfigurationManager.ActiveConfiguration;

            var swDimXPertMgr = swModel.Extension.DimXpertManager[swConfig.Name, true];
            var swDimXPertPart = (DimXpertPart)swDimXPertMgr.DimXpertPart;
            var swADSOpt = swDimXPertPart.GetAutoDimSchemeOption();

            swADSOpt.PartType = (int)swDimXpertAutoDimSchemePartType_e.swDimXpertAutoDimSchemePartType_Prismatic;
            swADSOpt.ToleranceType = (int)swDimXpertAutoDimSchemeToleranceType_e.swDimXpertAutoDimSchemeToleranceType_PlusMinus;
            swADSOpt.PatternType = (int)swDimXpertAutoDimSchemePatternType_e.swDimXpertAutoDimSchemePatternType_Linear;
            swADSOpt.PolarPatternHoleCount = 5;
            swADSOpt.ScopeAllFeature = false;
            boolstatus = swDimXPertPart.AutoDimensionScheme(swADSOpt);

            swModel.ClearSelection2(true);

            #endregion

运行结果:
效果还是可以的,时间有限,就写这么多了。

总结

这个对于简单零件来说还是特别方便的,复杂 的就需要去进行什么视图的处理了,不然太多尺寸一起显示,就太麻烦了。

posted @
2022-06-17 11:05 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源

SolidWorks二次开发API (C#)—删除草图中的错误关系

SolidWorks二次开发API (C#)—删除草图中的错误关系

下面这个图有没有见过?


是不是好像在哪见过,而且还比较讨厌?
这就是传说中的关系有问题了,这个关系就是大家常说的“关系”。自己想想这个关系重要不重要。

好了,正文到此结束。 大家耗子尾汁…


下面是菜单:

  1. 编辑草图
  2. 获取草图中的关系
  3. 删除错误的关系

首先打开我精心设计的一个零件:
大概用了十多年时间吧,不要问:

然后进行关键代码的编写:

不好意思 ,上面贴错了。。。

    /// <summary>
        /// 删除草图中的错误关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteRelation_Click(object sender, EventArgs e)
        {
            SldWorks swApp = PStandAlone.GetSolidWorks();

            var swModel = swApp.IActiveDoc2;

            //请先打开 D:\09_Study\CSharpAndSolidWorks\CSharpAndSolidWorks\TemplateModel\57_DeleteRelation.sldprt

            swModel.Extension.SelectByID2("Sketch11", "SKETCH", 0, 0, 0, false, 1, null, 0);
            swModel.EditSketch();

            swModel.ClearSelection2(true);

            var swSketch = swModel.IGetActiveSketch2();

            var skRelMgr = swSketch.RelationManager;

            var vRel = (object[])skRelMgr.GetRelations((int)swSketchRelationFilterType_e.swDangling + (int)swSketchRelationFilterType_e.swOverDefining);

            if (vRel != null)
            {
                for (int j = vRel.Length - 1; j >= 0; j--)
                {
                    var swSkRel = (SketchRelation)vRel[j];

                    //这一句是删除
                    skRelMgr.DeleteRelation(swSkRel);

                    //这一句是压缩掉 swSkRel.Suppressed = true;
                }
            }


            swModel.ForceRebuild3(true);




        }

执行还我漂漂拳之后 ,世界终于安静了。



如果真设计成这样,估计饭碗都保不住了。

这只是提供了一个思路,大家别想多了。

所有源代码获取:
https://gitee.com/painezeng/CSharpAndSolidWorks

https://github.com/painezeng/CSharpAndSolidWorks

posted @
2022-06-17 11:05 
painezeng  阅读(
0)  评论(
0
编辑 
收藏 
举报  
来源