首页 > 解决方案 > 如何将在 PictureBox 上绘制的图形复制到剪贴板?

问题描述

我有一个通过使用构建 3D 文本的软件,grafx.DrawString()我需要将此图形复制到剪贴板。当我尝试这样做时,它会引发 NullReferenceException。

如何复制在 PictureBox 上绘制的图形?

这是绘制文本的代码:

Dim grafx As Graphics
Private Sub draw_block_text10()
    Dim text_size As SizeF
    Dim back_brush As Brush = Brushes.Black 'COLOR FOR THE BOARDER TEXT
    Dim fore_brush As Brush = Brushes.Blue 'COLOR FOR THE MAIN TEXT


    Dim fnt As New Font("Microsoft Sans Serif", NumericUpDown1.Value, FontStyle.Regular)
    Dim location_x, location_y As Single 'USED IT FOR THE LOCATION
    Dim i As Integer

    'CREATE A GRAPHIC OBJECT IN THE PICTUREBOX.
    grafx = Me.PictureBox2.CreateGraphics()
    'CLEAR THE PICTUREBOX
    grafx.Clear(Color.White)

    'LOOK THE REQUIRED SIZE TO DRAW THE TEXT
    text_size = grafx.MeasureString(Me.TextBox1.Text, fnt)

    'ELIMINATE THE REDUNDANT CAlCULATION AFTER GETTING THE LOCATION.
    location_x = (Me.PictureBox2.Width - text_size.Width) / 2
    location_y = (Me.PictureBox2.Height - text_size.Height) / 2

    'FIRST, DRAW THE BLACK BACKGROUND TO GET THE EFFECT,
    'AND THE TEXT MUST BE DRAWN REAPETEDLY FROM THE OFFSET RIGHT, UP TO THE MAIN TEXT IS DRAWN.
    For i = CInt(nupDepth.Value) To 0 Step -1
        grafx.DrawString(TextBox1.Text, fnt, back_brush, _
        location_x - i, location_y + i)
    Next
    Dim mydataandtimeforsave = DateTime.Now.ToString("yyyyMMddHHmmss")
    'DRAW THE ROYAL BLUE FOR THE MAIN TEXT OVER THE BLACk TEXT
    grafx.DrawString(TextBox1.Text, fnt, fore_brush, location_x, location_y)
    Dim bmp As New Bitmap(Me.PictureBox2.Width, Me.PictureBox2.Height)
    Dim g As Graphics = Graphics.FromImage(bmp)
    g.Clear(Color.Transparent)

    ''Perform Drawing here

End Sub

这是复制到剪贴板的代码:

Clipboard.SetDataObject( _
    DirectCast(PictureBox2.Image.Clone, Bitmap), _
    True)
    Beep()

标签: vb.netwinformsgraphics

解决方案


使用Graphics从 PictureBox 控件 ( PictureBox.CreateGraphics()) 创建的对象进行绘图实际上不会设置/更改ImagePictureBox 的属性。您可以通过检查来确认,如果 PictureBox 在绘制之前没有图像PictureBox2.Image Is Nothing,它将返回 true 。

相反,Image使用 PictureBox 的尺寸创建一个,Graphics.FromImage()用于创建您的Graphics对象,绘制您需要绘制的内容,然后将图像分配给该PictureBox.Image属性。

像这样的东西应该可以正常工作:

Dim bmp As New Bitmap(PictureBox2.Width, PictureBox2.Height)
Using g As Graphics = Graphics.FromImage(bmp)
    g.Clear(Color.White)

    text_size = g.MeasureString(Me.TextBox1.Text, fnt)

    location_x = (Me.PictureBox2.Width - text_size.Width) / 2
    location_y = (Me.PictureBox2.Height - text_size.Height) / 2

    For i = CInt(nupDepth.Value) To 0 Step -1
        g.DrawString(TextBox1.Text, fnt, back_brush, location_x - i, location_y + i)
    Next

    g.DrawString(TextBox1.Text, fnt, fore_brush, location_x, location_y)
End Using

PictureBox2.Image = bmp

注意:当你使用完创建的 Graphics 对象时,请务必记得释放它,方法是调用.Dispose()或将其包装在我上面所做的Using语句中。


推荐阅读