表单中有一个用于绘制PictureBox形式的字段。为了查看鼠标位置的当前坐标,添加了一个Label元素。此元素附加到光标,而字段中的最后一个元素PictureBox
。
鼠标光标的工具提示代码:
public Label coordToolTip = new Label() { BorderStyle = BorderStyle.FixedSingle, BackColor = Color.WhiteSmoke, AutoSize = true };
向PictureBox添加工具提示:
this.pictureBox1.Controls.Add(coordToolTip);
启用/禁用/移动光标标签的事件:
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
coordToolTip.Visible = false;
this.Cursor = Cursors.Default;
}
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
if (this.pictureBox1.Image == null)
return;
coordToolTip.Visible = true;
this.Cursor = CursorUtil.CreateCursorNoResize(new Bitmap(Properties.Resources.Crosshair), 16, 16);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (this.pictureBox1.Image == null)
return;
int offsetX = coordToolTip.Size.Width + (e.X + 15) > this.pictureBox1.Width ? -(coordToolTip.Size.Width + 10) : 10;
int offsetY = coordToolTip.Size.Height + (e.Y + 15) > this.pictureBox1.Height ? -(coordToolTip.Size.Height + 10) : 10;
Point location = new Point(e.X, e.Y);
location.Offset(offsetX, offsetY);
coordToolTip.Location = location;
coordToolTip.Text = "X: " + e.X + "\nY: " + e.Y;
}
我使用以下代码从数组中绘制形状:
List<IntIntHolder> array = SHAPES[index];
Point[] points = new Point[array.Count];
for (int i = 0; i < array.Count; i++)
{
IntIntHolder holder = array[i];
points[i].X = holder.getKey();
points[i].Y = holder.getValue();
}
Graphics graph = this.pictureBox1.CreateGraphics();
Pen pen = new Pen(Brushes.Red, 2);
graph.DrawPolygon(pen, points);
最后,我按预期得到了一切。但!一旦光标后面的Label元素经过绘制的形状,该点的形状就会像橡皮擦一样被擦除。PictureBox图像本身不会改变。
但是在执行这段代码时
this.pictureBox1.Invalidate();
在所有图形消失之前,它们会再次出现/被绘制然后被删除。
问题:告诉我如何解决这个问题(我搞砸了),或者实现类似功能的方式是否更正确。
我在一个未命名的 Pole 的代码中找到了我的问题的解决方案(从本地化来看)。我在一个俄语论坛上找到了该项目本身(我丢失了该主题的链接),在其中一个主题中讨论了与我类似的问题。
解法的意思很简单。创建了一个包含各种几何形状的 UserControl。他还参与了他们的绘图和编辑(调整大小和拖动)。稍微扩展了功能后,我直接在控件本身内添加了光标的效果。
我附上了项目的链接。也许有人会派上用场,对如何在 WinForms 中绘图进行可视化研究。