Android Code Snippet Dotted lines

I need to have dotted lines in my UI. I searched the forum with "Dotted line" but could not find what I needed.

So I devised my little sub that draws dotted lines along a panel top or left with the choice of stroke width, as well as dot length and line color. A boolean parameter Vertical indicates if the line is to be along top or left.

It should be pretty easy to modify, to draw dotted borders, or to change the frequency of the dots. Right now dots and spaces have equal length, but it would not be very difficult to have spaces larger or smaller than the dot.

I am placing it here for the next user looking for that feature. Enjoy.

B4X:
Public Sub DrawDottedLine(Target As View, aColor As Int, StrokeWidth As Int, DotLength As Int, vertical As Boolean)
   Dim c As Canvas
      c.Initialize(Target)
   If vertical Then
       For i = 0 To Target.Height Step DotLength * 2
       c.DrawLine(0, i, 0, i + DotLength, aColor, StrokeWidth)
       Next
       Else
       For i = 0 To Target.Width Step DotLength * 2
       c.DrawLine(i, 0dip, i + DotLength, 0dip, aColor, StrokeWidth)
       Next
   End If
   Target.Invalidate
End Sub

To draw the lines, go for instance :
B4X:
DrawDottedLine(Panel1, 0xFF000000, 1, 10, False) 'horizontal
DrawDottedLine(Panel2, 0xFF000000, 1, 5, True) 'vertical
 

Sergey_New

Well-Known Member
Licensed User
Longtime User
Please tell me how to change your code so that the line starts in an arbitrary place on the panel. For example, it started at point 100 and ended at point 300.
 

William Lancee

Well-Known Member
Licensed User
Longtime User
I had this available...
For an arbitrary dotted line at any angle. For testing I circled the end points.
dotted.png



B4X:
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    cv.Initialize(Root)
    drawDottedLine(100, 500, 300, 100, xui.Color_Black, 2dip, 10dip)   
End Sub

Private Sub drawDottedLine(x1 As Float, y1 As Float, x2 As Float, y2 As Float, foreColor As Int, lineWidth As Int, segmentSize As Int)
    Dim lineLength As Float = Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
    Dim nSegments As Int = (lineLength + .5 * segmentSize) / (1.5 * segmentSize)
    Dim fract As Float = (lineLength + .5 * segmentSize) / lineLength

    Dim xIncr As Float = fract * (x2 - x1) / nSegments
    Dim xIncrLine As Float = .6667 * xIncr
    Dim yIncr As Float = fract * (y2 - y1) / nSegments
    Dim yIncrLine As Float =  .6667 * yIncr
    
    For i = 0 To nSegments - 1
        Dim xx1 As Float = x1 + i * xIncr
        Dim yy1 As Float = y1 + i * yIncr
        Dim xx2 As Float = xx1 + xIncrLine
        Dim yy2 As Float = yy1 + yIncrLine
        If i = nSegments - 1 Then
            cv.DrawLine(xx1, yy1, x2, y2, foreColor, lineWidth)
        Else
            cv.DrawLine(xx1, yy1, xx2, yy2, foreColor, lineWidth)
        End If
    Next
End Sub
 
Top