Create drawing Break View

Create drawing Break View

RolfEven
Enthusiast Enthusiast
308 Views
1 Reply
Message 1 of 2

Create drawing Break View

RolfEven
Enthusiast
Enthusiast

Hi,

I have been tinkering with in Inventor iLogic code that will create a horizontal Break on a drawing View. Code below will attempt to create or edit a break for the selected view. The width of the view after Break should be the chosen percentage of sheet width.

 

What I would like help with is candid feedback on:

  1. General advice on how to write the code in a better way. The two main Subs are mostly the same, but I had a hard time getting the break position calculation work properly, so I decided to split them.
  2. How to exit/stop the entire code when "If desiredWidth > currentWidth Then" on line 54 in Sub UpdateViewWithBreak and on line 141 in Sub UpdateViewWithoutBreak. Current code only exits the Sub.
  3. What is wrong with Sub CenterDimensionTextTwiceLoop. In order to get dimension centered I must center it twice. Same/similar thing with Sub UpdateViewWithBreak, have to run it twice in order to center the break.
  4. How to create a Sub that centers all dimension for the selected view automatically.

 

2024_05_31_21_53_51_Autodesk_Inventor_Professional_2020.png

Animated GIF.gif

 

'################################################################################
'#                                                                              #
'# Disclaimer:                                                                  #
'#   Use this code at your own risk. The author assumes no responsibility for   #
'#   any damage or loss caused by the use of this code. Ensure you have backups #
'#   of your files and data before running this code.                           #
'#                                                                              #
'################################################################################

Sub Main()
    ' Get the active drawing document and sheet
    Dim oDrawDoc As DrawingDocument
    Dim oSheet As Sheet
    oDrawDoc = ThisApplication.ActiveDocument
    oSheet = oDrawDoc.ActiveSheet

    ' Get the target view width percentage from the user
    Dim percentage As Double
    percentage = GetTargetPercentage()

    ' Select the drawing view
    Dim oDrawingView As DrawingView
    oDrawingView = SelectDrawingView()

    ' Exit if no view is selected
    If oDrawingView Is Nothing Then
        Exit Sub
    End If

    ' Determine if the view has a break and call the appropriate subroutine
    If oDrawingView.BreakOperations.Count > 0 Then
        UpdateViewWithBreak(oDrawingView, oSheet, percentage)
		UpdateViewWithBreak(oDrawingView, oSheet, percentage)
    Else
        UpdateViewWithoutBreak(oDrawingView, oSheet, percentage)
    End If

    ' Center the view and zoom to fit
    CenterAndZoom(oDrawingView)
	
    ' Select a dimension to center its text
    CenterDimensionTextTwiceLoop()

    Return
End Sub

Sub UpdateViewWithBreak(oDrawingView As DrawingView, oSheet As Sheet, percentage As Double)
    On Error GoTo ErrorHandler

    ' Sheet width in cm
    Dim sheetWidth As Double
    sheetWidth = oSheet.Width

    ' Desired view width as a percentage of the sheet width
    Dim desiredWidth As Double
    desiredWidth = sheetWidth * percentage

    ' Current width of the view in cm
    Dim currentWidth As Double
    currentWidth = oDrawingView.Width

    ' Check if the current width is less than the desired width
    If desiredWidth > currentWidth Then
        ' Display a messagebox notifying the user that the desired width cannot be achieved
        MessageBox.Show("Desired View Width (" & Format(desiredWidth * 10, "0.0") & " mm) is larger than Current View Width. The view may be too short to reach the desired width.", "View Width Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
        ' Exit the subroutine
        Exit Sub
    End If

    ' Define default gap value
    Dim gap As Double
    gap = 0.6

    ' Get the existing break operation
    Dim oBreakOperation As BreakOperation
    oBreakOperation = oDrawingView.BreakOperations.Item(1)
    Dim breakLength As Double
    breakLength = oBreakOperation.EndPoint.DistanceTo(oBreakOperation.StartPoint)

    ' Calculate the total adjustment needed to achieve the desired width
    Dim totalAdjustment As Double
    totalAdjustment = desiredWidth - currentWidth

    ' Adjust the start and end points of the break
    Dim halfAdjustment As Double
    halfAdjustment = totalAdjustment / 2

    ' Get the center point of the view
    Dim oCenter As Point2d
    oCenter = oDrawingView.Center

    ' Define the new start and end points of the break
    Dim newStartPoint As Point2d
    Dim newEndPoint As Point2d

    ' Calculate the new break points based on the existing break and the desired width
    newStartPoint = ThisApplication.TransientGeometry.CreatePoint2d(oCenter.X - (breakLength / 2) - halfAdjustment, oCenter.Y)
    newEndPoint = ThisApplication.TransientGeometry.CreatePoint2d(oCenter.X + (breakLength / 2) + halfAdjustment, oCenter.Y)

    ' Update the existing break operation
    oBreakOperation.StartPoint = newStartPoint
    oBreakOperation.EndPoint = newEndPoint
    oBreakOperation.Gap = gap

    ' Display all information in one message box
    Dim message As String
    message = "Break Status: With Break" & vbCrLf & _
              "Percentage: " & (percentage * 100) & "%" & vbCrLf & _
              "Sheet Width: " & sheetWidth & " cm" & vbCrLf & _
              "Desired Width: " & desiredWidth & " cm" & vbCrLf & _
              "Current Width: " & currentWidth & " cm" & vbCrLf & _
              "Total Adjustment: " & totalAdjustment & " cm" & vbCrLf & _
              "New View Width: " & desiredWidth & " cm" & vbCrLf & _
              "Break Length: " & breakLength & " cm" & vbCrLf & _
              "New Start Point: (" & newStartPoint.X & ", " & newStartPoint.Y & ")" & vbCrLf & _
              "New End Point: (" & newEndPoint.X & ", " & newEndPoint.Y & ")"

    ' Display the updated view width
    Dim updatedWidth As Double
    updatedWidth = oDrawingView.Width
    message = message & vbCrLf & "Updated View Width: " & updatedWidth & " cm"

'    MessageBox.Show(message, "View Width Information")

    Exit Sub

ErrorHandler:
    MessageBox.Show("An error occurred: " & Err.Description, "Error")
    Err.Clear
End Sub



Sub UpdateViewWithoutBreak(oDrawingView As DrawingView, oSheet As Sheet, percentage As Double)
    On Error GoTo ErrorHandler

    ' Sheet width in cm
    Dim sheetWidth As Double
    sheetWidth = oSheet.Width

    ' Desired view width as a percentage of the sheet width
    Dim desiredWidth As Double
    desiredWidth = sheetWidth * percentage

    ' Current width of the view in cm
    Dim currentWidth As Double
    currentWidth = oDrawingView.Width

    ' Check if the desired view width is larger than the current view width
    If desiredWidth > currentWidth Then
        ' Notify the user and exit the subroutine
MessageBox.Show("Desired View Width (" & Format(desiredWidth * 10, "0.0") & " mm) is larger than Current View Width (" & Format(currentWidth * 10, "0.0") & " mm). Exiting.", "Desired View Width is too large")
        Exit Sub
    End If

    ' Define default gap value
    Dim gap As Double
    gap = 0.6

    ' Calculate the total adjustment needed to achieve the desired width
    Dim totalAdjustment As Double
    totalAdjustment = desiredWidth - currentWidth - gap

    ' Adjust the start and end points of the break
    Dim halfAdjustment As Double
    halfAdjustment = totalAdjustment / 2

    ' Get the center point of the view
    Dim oCenter As Point2d
    oCenter = oDrawingView.Center

    ' Define the new start and end points of the break
    Dim newStartPoint As Point2d
    Dim newEndPoint As Point2d

    ' Calculate the new break points based on the desired width (no existing break)
    newStartPoint = ThisApplication.TransientGeometry.CreatePoint2d(oCenter.X - halfAdjustment, oCenter.Y)
    newEndPoint = ThisApplication.TransientGeometry.CreatePoint2d(oCenter.X + halfAdjustment, oCenter.Y)

    ' Apply a new break operation
    Dim oBreakOperation As BreakOperation
    oBreakOperation = oDrawingView.BreakOperations.Add(BreakOrientationEnum.kHorizontalBreakOrientation, newStartPoint, newEndPoint, BreakStyleEnum.kStructuralBreakStyle, 5)

    ' Display all information in one message box
    Dim message As String
    message = "Break Status: Without Break" & vbCrLf & _
              "Percentage: " & (percentage * 100) & "%" & vbCrLf & _
              "Sheet Width: " & sheetWidth & " cm" & vbCrLf & _
              "Desired Width: " & desiredWidth & " cm" & vbCrLf & _
              "Current Width: " & currentWidth & " cm" & vbCrLf & _
              "Total Adjustment: " & totalAdjustment & " cm" & vbCrLf & _
              "New View Width: " & desiredWidth & " cm" & vbCrLf & _
              "New Start Point: (" & newStartPoint.X & ", " & newStartPoint.Y & ")" & vbCrLf & _
              "New End Point: (" & newEndPoint.X & ", " & newEndPoint.Y & ")"

    ' Display the updated view width
    Dim updatedWidth As Double
    updatedWidth = oDrawingView.Width
    message = message & vbCrLf & "Updated View Width: " & updatedWidth & " cm"

'    MessageBox.Show(message, "View Width Information")

    Exit Sub

ErrorHandler:
    MessageBox.Show("An error occurred: " & Err.Description, "Error")
    Err.Clear
End Sub


' Function to get the target percentage from the user
Function GetTargetPercentage() As Double
    Dim percentageInput As String
    percentageInput = InputBox("Enter the desired width of the drawing view as a percentage of the sheet width.", "Target View Width Size", "50")

    Dim percentage As Double
    If Double.TryParse(percentageInput, percentage) = False Then
        percentage = 50 ' Default value if parsing fails
    End If

    ' Ensure the percentage is within the valid range (0-100)
    percentage = Math.Max(0, Math.Min(100, percentage))

    ' Convert the percentage to a fraction (e.g., 50% becomes 0.5)
    Return percentage / 100
End Function

' Function to select a drawing view
Function SelectDrawingView() As DrawingView
    On Error GoTo ErrorHandler
    Dim oViewSelect As DrawingView
    oViewSelect = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kDrawingViewFilter, "Select a view to apply or update break. Press 'Esc' to exit.")
    Return oViewSelect

ErrorHandler:
    MessageBox.Show("Failed to select a drawing view.", "Error")
    Return Nothing
End Function

' Subroutine to center the view and zoom to fit
Sub CenterAndZoom(oDrawingView As DrawingView)
    Dim oCenter As Point2d
    oCenter = oDrawingView.Center

    ' Center the view
    oDrawingView.Center = oCenter

    ' Zoom to fit the new view area
    ThisApplication.CommandManager.ControlDefinitions.Item("AppZoomAllCmd").Execute
End Sub

' Subroutine to center text for dimensions in the active sheet twice with the option to exit the loop using user input
Sub CenterDimensionTextTwiceLoop()
    Dim selectedDimension As DrawingDimension

    ' Loop until the user cancels the selection (presses Esc)
    Do
        ' Select a dimension
        selectedDimension = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kDrawingDimensionFilter, "Select a dimension to center. Press 'Esc' to exit.")

        ' Exit the loop if nothing is selected
        If selectedDimension Is Nothing Then
            Exit Do
        End If

        ' Try to center the dimension text twice
        Dim errorOccurred As Boolean
        errorOccurred = False

        On Error Resume Next
        selectedDimension.CenterText
        If Err.Number <> 0 Then
            errorOccurred = True
        End If

        selectedDimension.CenterText
        If Err.Number <> 0 Then
            errorOccurred = True
        End If
        On Error GoTo 0

        If errorOccurred Then
            MessageBox.Show("The selected dimension is not supported.", "Error")
        End If

        ' Continue to the next iteration
        Continue Do

    Loop
End Sub

 

/Rolf Even

0 Likes
309 Views
1 Reply
Reply (1)
Message 2 of 2

JelteDeJong
Mentor
Mentor

Just some tips don't use:
ThisApplication.ActiveDocument
but use:
ThisDoc.Document

(link)

 

stop using:
On Error ....
but use:

Try
    ' Your code that can crash here
Catch ex As Exception
   ' Handle crash here
End Try

(link)

 

you can declare and set a variable in one line. instead of this:
Dim sheetWidth As Double
sheetWidth = oSheet.Width
use:
Dim sheetWidth As Double = oSheet.Width

 

Write fewer comments. The code should be self-explaining

I discovered that if you delete the "break" and (re) create it, all dimensions get centred automatically.

I would write the function like this:

 

Public Class ThisRule
    Sub Main()
        Dim oDrawDoc As DrawingDocument = ThisDoc.Document
        Dim oSheet As Sheet = oDrawDoc.ActiveSheet

        Dim percentage As Double = GetTargetPercentage()
        Dim oDrawingView As DrawingView = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kDrawingViewFilter, "Select a view to apply or update break. Press 'Esc' to exit.")

        If oDrawingView Is Nothing Then
            MessageBox.Show("Failed to select a drawing view.", "Error")
            Exit Sub
        End If

        UpdateBreak(oDrawingView, oSheet, percentage)
        CenterAndZoom(oDrawingView)
    End Sub

    Private Sub UpdateBreak(view As DrawingView, sheet As Sheet, percentage As Double)
        Dim gap As Double = 0.6
        Dim oTg = ThisApplication.TransientGeometry

        If view.BreakOperations.Count > 0 Then
            Dim breakOperationOld As BreakOperation = view.BreakOperations.Item(1)
            breakOperationOld.Delete()
        End If

        Dim sheetWidth As Double = sheet.Width
        Dim desiredWidth As Double = sheetWidth * percentage
        Dim currentWidth As Double = view.Width
        Dim viewCenter = view.Center

        Dim breakLength As Double = sheetWidth - desiredWidth - currentWidth - gap

        Dim startPoint As Point2d = oTg.CreatePoint2d(viewCenter.X - (breakLength / 2), viewCenter.Y)
        Dim endPoint As Point2d = oTg.CreatePoint2d(viewCenter.X + (breakLength / 2), viewCenter.Y)

        Dim breakOperation As BreakOperation = view.BreakOperations.Add(BreakOrientationEnum.kHorizontalBreakOrientation, startPoint, endPoint, BreakStyleEnum.kStructuralBreakStyle, 5)
        breakOperation.Gap = gap
    End Sub

    Function GetTargetPercentage() As Double
        Dim percentageInput As String = InputBox(
            "Enter the desired width of the drawing view as a percentage of the sheet width.",
            "Target View Width Size", "50")

        Dim percentage As Double
        If Not Double.TryParse(percentageInput, percentage) Then
            percentage = 50 ' Default value if parsing fails
        End If

        percentage = Math.Max(0, Math.Min(100, percentage))
        Return percentage / 100
    End Function

    Sub CenterAndZoom(oDrawingView As DrawingView)
        ThisApplication.CommandManager.ControlDefinitions.Item("AppZoomAllCmd").Execute()
    End Sub
End Class

 

 

Jelte de Jong
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

EESignature


Blog: hjalte.nl - github.com