Search code examples
for-loopvb.net-2010populatedrawrectangle

Automatic alignment of rectangle depend of size of paper in vb.net


I have rectangle that's add another rectangle depend on how many stamps/receipt to be print.

I add another rectangle using for loop but if I manage to add more than 3 rectangles the other rectangles will not diplay because it's keeping align straight or if I use if else if e.pagebounds.widht < (the last width of my rectangle) it goes down and it's fine but how about the next... next ... next for the row 3 and up how can I get that this is my code so far

Dim rec As Rectangle

    Dim x1, y1 As Integer
    Dim nextline As Integer
    x1 = 40
    y1 = 40
    Dim b As Integer = 0
    Dim containerrectangle As Rectangle
    containerrectangle = New Rectangle(e.PageBounds.X, e.PageBounds.Y, e.PageBounds.Width, e.PageBounds.Height)
    For i = 0 To 6
        If e.PageBounds.Width - 100 < x1 + b Then
            nextline = 40
            'reset the x-axis of the rectangle
            y1 = 250
            b = 40
            rec = New Rectangle(b, y1 + 50, 250, 250)
            e.Graphics.DrawRectangle(Pens.Sienna, rec)
            y1 += 250
            b += 10
        Else
            rec = New Rectangle(x1 + b, 40, 250, 250)
            e.Graphics.DrawRectangle(Pens.Sienna, rec)
            x1 += 250
            b += 10
        End If
    Next

please see image https://i.sstatic.net/kGDJh.jpg


Solution

  • Have a look into this code - I'd say it's more straight forward:

        Dim RectTemplate As New Rectangle(0, 0, 250, 250)
    
    
        Dim GapPx As Int32 = 12                    ' set gap between rectangles
        Dim StaPt As New Point(GapPx, GapPx * 2)   ' set starting point
        Dim N As Int32 = 15                        ' set (or get) the totalnumber of rectangles
        Dim nL As Int32 = Math.Floor((e.PageBounds.Width - GapPx) / (RectTemplate.Width + GapPx))  ' number of rectangles per row
        Dim nR As Int32 = Math.Ceiling(N / nL)   ' number of rows of rectangles 
    
        For ir = 0 To nR - 1       ' process all rows
            For il = 0 To nL - 1   ' process all rectangles in a row
                Dim rect As New Rectangle(StaPt.X + il * (RectTemplate.Width + GapPx), StaPt.Y + ir * (RectTemplate.Height + GapPx), RectTemplate.Width, RectTemplate.Height)
                e.graphics.DrawRectangle(Pens.Sienna, rect)
            Next
        Next