2017-09-03 138 views
1

我是vb.net的新手,我想在圖像上添加一些文字,但似乎我的代碼根本無法使用。在圖像中添加文字vb.net

Public Class Form1 
    Dim Graph As Graphics 
    Dim Drawbitmap As Bitmap 
    Dim Brush As New Drawing.SolidBrush(Color.Black) 
    Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As EventArgs) 
     Drawbitmap = New Bitmap(PictureBox1.Width, PictureBox1.Height) 
     Graph = Graphics.FromImage(Drawbitmap) 
     PictureBox1.Image = Drawbitmap 
     Graph.SmoothingMode = Drawing2D.SmoothingMode.HighQuality 
     Graph.DrawString(RichTextBox1.Text, RichTextBox1.Font, Brush, PictureBox1.Location) 


    End Sub 
End Class 
+0

文本?就像在後臺有一些文字在前景中的圖像? –

+0

你不刷新PictureBox。 – jAC

回答

1

您的代碼有許多問題。首先,你不會處置已經在PictureBox中的Bitmap。其次,你不會配置你創建的Graphics對象來繪製文本。第三,雖然它不應該是一個主要問題,但我想不出爲什麼你會認爲首先顯示Bitmap然後繪製文本是一個好主意。

最後,可能是您沒有看到任何文本的原因是,您正在使用PictureBox1.Location指定在哪裏繪製文本。這是沒有意義的,因爲這意味着PictureBox距離表格的左上角越遠,文字將從Bitmap的左上角越遠。你需要考慮一下你真正想要在Bitmap上繪製文字的位置。

下面是一些測試代碼,解決了所有這些問題:

Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged 
    Dim img As New Bitmap(PictureBox1.Width, PictureBox1.Height) 

    Using g = Graphics.FromImage(img) 
     g.SmoothingMode = SmoothingMode.HighQuality 
     g.DrawString(RichTextBox1.Text, RichTextBox1.Font, Brushes.Black, New PointF(10, 10)) 
    End Using 

    'Dispose the existing image if there is one.' 
    PictureBox1.Image?.Dispose() 

    PictureBox1.Image = img 
End Sub 

注意,代碼也使用系統提供的Brush,而不是無謂地創建一個也沒有配置。

注意,這條線將僅在2017年VB工作:

PictureBox1.Image?.Dispose() 

在早期版本中,你將需要一個If聲明:在圖像上如何

If PictureBox1.Image IsNot Nothing Then 
    PictureBox1.Image.Dispose() 
End If 
+0

謝謝@jmcilhinney工作就像一個魅力!並感謝你向我解釋它澄清了一切 –