ElektroStudios
ElektroStudios

Reputation: 20464

Draw proportional triangle inside control

Maths are not my speciality and as this is more a math question than a VB question I tagged it with C# tag too.

I need help to draw a triangle inside the working area (client rectangle) of a custom user control but I fail setting the right coordinates (I fail trying to calculate the right coordinates doing operations with Me.Left, Me.Right, Me.Top and Me.Bottom...), here is the relevant code to draw the rectangle:, but anyways I'm not sure whether I'm using the beast approach (because the control's client rectangle area).

    Dim ptsArray As PointF() =
        {
            New PointF(0, 0),
            New PointF(0, 0),
            New PointF(0, 0),
            New PointF(0, 0)
        }

    Dim gp As New Drawing2D.GraphicsPath(Drawing2D.FillMode.Alternate)
    gp.AddLines(ptsArray)
    gp.CloseFigure()

    e.Graphics.FillPath(Brushes.Red, gp)
    e.Graphics.DrawLines(Pens.Black, ptsArray)

If this is my control:

enter image description here

The rectangle result should be like this, as you'll see the rectangle respects the proportions/size of the control:

enter image description here

Upvotes: 0

Views: 1078

Answers (1)

Here's an example of how to draw a triangle. Note that you also need take the width of the pen into the equations. Also, you need to draw the path, not the lines.

pt1: top center, pt2: bottom - right, pt3: bottom - left.

Using pen As New Pen(Brushes.Red, 10)

    Dim rect As Rectangle = Me.ClientRectangle
    Dim pt1 As New PointF(CSng(rect.Left + (rect.Width / 2)), (rect.Top + pen.Width))
    Dim pt2 As New PointF((rect.Right - pen.Width), (rect.Bottom - pen.Width))
    Dim pt3 As New PointF((rect.Left + pen.Width), (rect.Bottom - pen.Width))

    Using path As New Drawing2D.GraphicsPath(FillMode.Winding)
        path.AddLines({pt1, pt2, pt3, pt1})
        path.CloseFigure()
        e.Graphics.DrawPath(pen, path)
    End Using

End Using

Upvotes: 2

Related Questions