none
关于在PictureBox中绘图,当窗口被掩盖时窗口无法重绘的问题 RRS feed

  • 问题

  • 我用的是vb.net 2010窗体中有一个PictureBox控件和一个Button控件,窗体启动后按Button控件会在PictureBox控件中绘一些线框,当这个窗口被掩盖或窗口尺寸改变后,以前绘的东西都不见了,如何解决?

    下面是窗体中的代码,请高手给指点一下哪里有问题,谢谢。

    Imports System.Drawing.Drawing2D
    Public Class Form1
        Dim BlackPen As Pen
        Dim gr As Graphics
        Dim bm As New Bitmap(880, 100)
        Dim gPath1 As GraphicsPath
        Dim graph As Graphics
        Dim tempArray(19) As Boolean
        Dim myArray As Point()
        Sub New()
            ' 此调用是设计器所必需的。
            InitializeComponent()
            ' 在 InitializeComponent() 调用之后添加任何初始化。
            gr = PictureBox1.CreateGraphics
            BlackPen = New Pen(Brushes.Red, 1.7)
            graph = Graphics.FromImage(bm)
            graph.SmoothingMode = SmoothingMode.AntiAlias
        End Sub
        Private Sub PictureBox1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
            PlotData()
        End Sub
        Private Sub PlotData()
            graph.FillRectangle(Brushes.WhiteSmoke, 0, 0, 880, 100) '清除画布
            Dim pen1 As Pen = New Pen(Color.Green, 1.5) '实线
            Dim pen2 As Pen = New Pen(Color.Green, 0.01) '实线
            Dim gPath1 As GraphicsPath = New GraphicsPath '路径1
            Dim gPath2 As GraphicsPath = New GraphicsPath '路径2
            Dim pathRect As New Rectangle '矩形路径
            For i As Integer = 20 To 850 Step 42 '循环20次
                pathRect = New Rectangle(i, 20, 42, 26) '创建矩形路径的尺寸
                gPath1.AddRectangle(pathRect) '添加矩形
                gPath2.AddEllipse(i + 6, 24, 7, 7) '添加左边圆形
                gPath2.AddEllipse(i + 29, 24, 7, 7) '添加右边圆形
                graph.DrawLine(pen1, i + 7, 38, i + 12, 38) '画正号 横
                graph.DrawLine(pen1, CSng(i + 9.5), CSng(35.5), CSng(i + 9.5), CSng(40.5)) '画正号 负
                graph.DrawLine(pen1, i + 30, 38, i + 35, 38) '画负号
                graph.DrawPath(pen1, gPath1) '画路径1
                graph.DrawPath(pen2, gPath2) '画路径2
            Next
            PictureBox1.CreateGraphics.DrawImage(bm, 0, 0)
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            PlotData()
        End Sub
    End Class


    myriceme

    2012年5月9日 8:57

答案

  • 将这一行:PictureBox1.CreateGraphics.DrawImage(bm, 0, 0)

    替换为下面一行即可

    PictureBox1.Image = bm

    是这样的吗?


    学无止境

    • 已标记为答案 lilin 2012年5月9日 12:43
    2012年5月9日 9:27

全部回复