问题
I am new to vb.net and I want to add some text on the image but it seems my code is not working at all.
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
回答1:
There are a number of issues with your code. Firstly, you're not disposing of the Bitmap
that is already in the PictureBox
. Secondly, you're not disposing the Graphics
object you create to draw the text. Thirdly, while it shouldn't be a major issue, I can't think why you'd think it was a good idea to display the Bitmap
first and then draw the text.
Finally, and probably the reason that you're not seeing any text, is the fact that you're using PictureBox1.Location
to specify where to draw the text. That makes no sense because that means that the further the PictureBox
is from the top-left of the form, the further the text will be from the top-left of the Bitmap
. You need to put some thought into where you actually want the text to be drawn on the Bitmap
.
Here's some tested code that addresses all those issues:
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
Note that that code also uses a system-supplied Brush
, instead of needlessly creating one that is also not disposed.
Note that this line will only work in VB 2017:
PictureBox1.Image?.Dispose()
In earlier versions you would need an If
statement:
If PictureBox1.Image IsNot Nothing Then
PictureBox1.Image.Dispose()
End If
来源:https://stackoverflow.com/questions/46021397/adding-text-in-an-image-vb-net