Come verificare se un testo può essere visualizzato in un area prefissata

 

Questa funzione permette di verificare se un testo è visualizzabile integralmente in un area prefissata e può essere utile nei casi in cui si voglia visualizzare un ToolTip per testi che superano lo spazio messo a disposizione da un controllo (xes. un tooltip sugli item di un ListView in modalità dettaglio il cui testo supera la larghezza della colonna)

Public Function IsTextExceedSize(ByVal graphics As System.Drawing.Graphics, _
                                                     ByVal text As String, _
                                                     ByVal font As System.Drawing.Font, 
                                                     ByVal width As Integer, _
                                                     ByVal height As Integer) As Boolean

   Dim textSize As System.Drawing.SizeF
   Dim charactersFitted, linesFitted As Integer
   Dim layoutRect As New System.Drawing.SizeF(width, height)

   textSize = graphics.MeasureString(text, font, layoutRect, _
                        System.Drawing.StringFormat.GenericTypographic, _
                        charactersFitted, linesFitted)

   layoutRect = Nothing

   If textSize.Width > width Then Return True

   If textSize.Height > height Then Return True

  Return text.Length > charactersFitted
End Function