gpt4 book ai didi

c# - 如何使用c#绘制多个矩形

转载 作者:行者123 更新时间:2023-11-30 22:45:39 25 4
gpt4 key购买 nike

我已经在加载到图片框中的图像上绘制并保存了矩形。我多么喜欢为此绘制多个矩形,我在矩形中尝试了数组,但它给出了错误(“对象引用未设置到对象的实例。”(空引用异常未处理)。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com