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



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

如何复制在图片框上绘制的图形?

这是绘制文本的代码:

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()

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

而不是

Clipboard.SetDataObject(DirectCast(PictureBox2.Image.Clone, Bitmap(, true(

Clipboard.SetDataObject(PictureBox2.Image, 2)

最新更新