Mega Code Archive

 
Categories / VB.Net Tutorial / 2D Graphics
 

Measure string and draw rectangle around string

Imports System Imports System.Drawing Imports System.Collections Imports System.ComponentModel Imports System.Windows.Forms Imports System.Globalization public class GraphicsMeasureStringRectangle    public Shared Sub Main         Application.Run(New Form1)    End Sub End class Public Class Form1     Inherits System.Windows.Forms.Form     Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint         Dim g As Graphics = e.Graphics         Dim s As String = "a multi-line string:" & vbCrLf & "line 2" & vbCrLf & "line 3"         Dim y As Single = 0         Dim arrPens As Pen() = New Pen() {Pens.Red, Pens.Green, Pens.Blue}         Dim line As String         For Each line In s.Split(vbCrLf)             Dim width As Single = ClientRectangle.Width             Dim height As Single = ClientRectangle.Height - y             Dim layoutRect As RectangleF = New RectangleF(0, y, width, height)             Dim format As StringFormat = New StringFormat(StringFormatFlags.NoWrap Or StringFormatFlags.DisplayFormatControl)             g.DrawString(line, Me.Font, Brushes.Black, layoutRect, format)             Dim size As SizeF = g.MeasureString(line, Me.Font, layoutRect.Size, format)             g.DrawRectangle(arrPens(CInt(y / Me.Font.GetHeight(g))), 0, y, size.Width, size.Height)             y = y + Me.Font.GetHeight(g)         Next     End Sub     Public Sub New()         MyBase.New()         InitializeComponent()     End Sub     Private components As System.ComponentModel.IContainer     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()         Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)         Me.ClientSize = New System.Drawing.Size(20, 60)         Me.Name = "Form1"         Me.Text = "Form1"         Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))     End Sub End Class