我有一个软件,通过使用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()
2条答案
按热度按时间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
属性。类似这样的操作应该可以正常工作:
注意:在使用完创建的Graphics对象后,一定要记住通过调用
.Dispose()
或像上面所做的那样将其 Package 在Using
statement中来处置它。643ylb082#
代替
(DirectCast(图片框2.图像.克隆,位图),True)
用途