Heute zeigen wir Ihnen, wie sich ein beliebiger Text (auch mehrzeiliger Text) mit .NET Boardmitteln sehr einfach in eine Grafik (Bitmap-Objekt) umwandeln lässt. Neben dem Text selbst lässt sich die Schrift, Vordergrund- und Hintergrundfarbe, sowie der Abstand des Textes zum "Bildrahmen" festlegen. Imports System.Drawing ... ''' <summary> ''' Wandelt Text in ein Bitmap um ''' </summary> ''' <param name="Text">Text, der als Grafik dargestellt werden soll.</param> ''' <param name="Font">Font-Objekt für die Schriftart, Größe und Attribute des Textes</param> ''' <param name="ForeColor">Textfarbe</param> ''' <param name="BackColor">Hintergrundfarbe des Bitmaps</param> ''' <param name="Padding">x und y Abstand des Textes zum Bild</param> ''' <returns>Bitmap-Objekt</returns> ''' <remarks>Der Text kann auch Zeilenumbrüche enthalten.</remarks> Public Function Text2Image(ByVal Text As String, ByVal Font As Font, ByVal ForeColor As Color, _ ByVal BackColor As Color, ByVal Padding As Point) As Image ' Textgröße (Maße) ermitteln Dim txtSize As Size = TextRenderer.MeasureText(Text, Font) Dim imgWidth As Integer = txtSize.Width + Padding.X * 2 Dim imgHeight As Integer = txtSize.Height + Padding.Y + 2 ' Vordergrund-/Hintergrundfarbe Dim BrushForeColor As SolidBrush = New SolidBrush(ForeColor) Dim BrushBackColor As SolidBrush = New SolidBrush(BackColor) ' Neues Bitmap-Objekt erstellen Dim Bitmap As New Bitmap(imgWidth, imgHeight) Using imgGraphics As Graphics = Graphics.FromImage(Bitmap) ' Rechteck füllen imgGraphics.FillRectangle(BrushBackColor, 0, 0, imgWidth, imgHeight) ' Text zeichnen imgGraphics.DrawString(Text, Font, BrushForeColor, Padding) End Using ' Bitmap zurückgeben Return Bitmap End Function Aufrufbeispiel: Dim Text As String = "vb@rchiv" & vbCrLf & "www.vbarchiv.net" ' Text als Grafik in einer PictureBox anzeigen PictureBox1.Image = Text2Image(Text, Me.Font, New Font("Verdana", 9, FontStyle.Bold), _ Color.Black, Color.White, New Point(5, 5)) |