WinForms:PictureBox初始化问题

时间:2013-11-06 13:00:38

标签: c# image draw picturebox

如果我将PictureBox初始化放入表单的构造函数或form.Load / form.Shown处理程序,则PictureBox上不会绘制任何内容。如果在绘图之前进行初始化,则会出现图形。

为什么此代码在PictureBox上绘制数组:

public partial class Form1 : Form
{
    Bitmap drawArea;

    public Form1()
    {
        InitializeComponent();
    }

    private void drawArray(int[] arr, PictureBox box)
    {
        //=========== Attention to this code ================
        drawArea = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
        pictureBox1.Image = drawArea;
        //===================================================
        using (Graphics g = Graphics.FromImage(drawArea))
        {
            Pen mypen = new Pen(Brushes.Black);
            g.Clear(Color.White);
            for (int i = 0; i < arr.Length; i++)
                g.DrawLine(mypen, i*2, drawArea.Height,
                   i*2, drawArea.Height - arr[i]);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int[] ar1 = randomArray(20, 1, 20);
        drawArray(ar1, pictureBox1);
    }
}

但是这段代码没有?

public partial class Form1 : Form
{
    Bitmap drawArea;

    public Form1()
    {
        InitializeComponent();
        //=========== Attention to this code ================
        //Breakpoint here: pictureBox1.Size.Width==409, pictureBox1.Size.Height==205
        drawArea = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
        pictureBox1.Image = drawArea;
        //===================================================
    }

    private void drawArray(int[] arr, PictureBox box)
    {
        using (Graphics g = Graphics.FromImage(drawArea))
        {
            Pen mypen = new Pen(Brushes.Black);
            g.Clear(Color.White);
            for (int i = 0; i < arr.Length; i++)
                g.DrawLine(mypen, i*2, drawArea.Height,
                  i*2, drawArea.Height - arr[i]);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int[] ar1 = randomArray(20, 1, 20);
        drawArray(ar1, pictureBox1);
    }
}

如果我创建第二个按钮并将初始化代码放在其处理程序中(当然,在点击第一个按钮之前单击第二个按钮),它甚至不起作用。

没有抛出异常。

1 个答案:

答案 0 :(得分:1)

不确定...只是在drawArray()中对PictureBox进行Invalidate(),以便自行刷新:

    private void drawArray(int[] arr, PictureBox box)
    {
        using (Graphics g = Graphics.FromImage(drawArea))
        {
            Pen mypen = new Pen(Brushes.Black);
            g.Clear(Color.White);
            for (int i = 0; i < arr.Length; i++)
                g.DrawLine(mypen, i * 2, drawArea.Height,
                  i * 2, drawArea.Height - arr[i]);
        }
        box.Invalidate();
    }

*如果您没有使用PictureBox,为什么还要通过PictureBox?