如何将在PictureBox上绘制的图形复制到剪贴板?

时间:2018-07-01 11:54:39

标签: vb.net winforms graphics

我有一个使用grafx.DrawString()构建3D文本的软件,我需要将此图形复制到剪贴板。当我尝试这样做时,它将引发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()

1 个答案:

答案 0 :(得分:1)

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

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

类似的东西应该可以正常工作:

PictureBox.Image

注意:请务必记住,在使用完创建的Graphics对象后,可以通过调用.Dispose()或将其包装在Using statement中来处置它,就像我之前所做的那样。