在图像中添加文本 vb.net [英] Adding text in an image vb.net

查看:38
本文介绍了在图像中添加文本 vb.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 vb.net 的新手,我想在图像上添加一些文本,但我的代码似乎根本不起作用.

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

推荐答案

您的代码存在许多问题.首先,您不会处理已经在 PictureBox 中的 Bitmap.其次,您不会处理您创建的用于绘制文本的 Graphics 对象.第三,虽然它不应该是一个主要问题,但我想不出为什么你会认为先显示 Bitmap 然后绘制文本是个好主意.

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.

最后,也许您没有看到任何文本的原因是您使用 PictureBox1.Location 来指定在何处绘制文本.这是没有意义的,因为这意味着 PictureBox 离表单的左上角越远,文本离 Bitmap 的左上角就越远.您需要考虑在 Bitmap 上实际要绘制文本的位置.

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

请注意,该代码还使用了系统提供的 Brush,而不是不必要地创建了一个也未处理的.

Note that that code also uses a system-supplied Brush, instead of needlessly creating one that is also not disposed.

请注意,此行仅适用于 VB 2017:

Note that this line will only work in VB 2017:

PictureBox1.Image?.Dispose()

在早期版本中,您需要一个 If 语句:

In earlier versions you would need an If statement:

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

这篇关于在图像中添加文本 vb.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆