如果我将 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);
}
}
如果我制作第二个按钮并将初始化代码放入其处理程序中(当然在单击第一个按钮之前单击第二个按钮),它甚至都不起作用。
不会抛出异常。