我已经在图片框中加载的图像上绘制并保存了矩形。我如何喜欢绘制多个矩形,因为我在矩形中尝试了数组,但它给出了错误(“对象引用未设置为对象的实例。”(空引用异常未处理)。
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (mybitmap == null)
{
mybitmap = new Bitmap(sz.Width, sz.Height);
}
rect[count] = new Rectangle(e.X, e.Y, 0, 0);
this.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (stayToolStripMenuItem.Checked == true)
{
switch (e.Button)
{
case MouseButtons.Left:
{
rect[count] = new Rectangle(rect[count].Left, rect[count].Top, e.X - rect[count].Left, e.Y - rect[count].Top);
pictureBox1.Invalidate();
count++:
break;
}
}
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (stayToolStripMenuItem.Checked == true)
{
button1.Visible = true;
button2.Visible = true;
if (mybitmap == null)
{
return;
}
using (g = Graphics.FromImage(mybitmap))
{
using (Pen pen = new Pen(Color.Red, 2))
{
//g.Clear(Color.Transparent);
e.Graphics.DrawRectangle(pen, rect);
label1.Top = rect[count].Top; label1[count].Left = rect[count].Left; label1.Width = rect[count].Width;
label1.Height = rect[count].Height;
if (label1.TextAlign == ContentAlignment.TopLeft)
{
e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect);
g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect);
g.DrawRectangle(pen, rect[count]);
}
}
}
}
}
我该怎么做......
最佳答案
您正在增加 count
填充 rect
后的变量大批。到时候pictureBox1_Paint
执行后,这个增量已经发生,所以 rect[count]
现在是一个空引用,然后您尝试绘制它:)
此外,pictureBox1_MouseDown
中似乎存在编译器错误。 。 count++
里面switch
声明不属于任何 case
堵塞。将其放在 break;
之前声明。
我想你的意图是这样的:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (mybitmap == null)
return;
using (g = Graphics.FromImage(mybitmap))
using (Pen pen = new Pen(Color.Red, 2))
{
g.Clear(Color.Transparent);
for (int i = 0; i < count; i++)
{
// Code to draw rect[i], instead of rect[count]
}
}
}
你的 rect
有多大?顺便问一下,数组?数组不会自动增长以满足您的需求。您可能想查看使用 List<Rectangle>
相反。
关于c# - 如何使用c#绘制多个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2948479/