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

weylhg0b  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(146)

我有一个软件,通过使用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()
v9tzhpje

v9tzhpje1#

使用从PictureBox控件(PictureBox.CreateGraphics())创建的Graphics对象进行绘制实际上不会设置/更改PictureBox的Image属性。您可以通过检查PictureBox2.Image Is Nothing来确认这一点,如果在PictureBox上绘制之前 * PictureBox没有图像,则PictureBox2.Image Is Nothing将返回true。
而是使用PictureBox的尺寸创建Image,使用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()或像上面所做的那样将其 Package 在Using statement中来处置它。

643ylb08

643ylb082#

代替
(DirectCast(图片框2.图像.克隆,位图),True)
用途

Clipboard.SetDataObject(PictureBox2.Image, 2)

相关问题