[英]Draw lines on a PictureBox
我的问题与“堆栈溢出”问题有关, 在C#中使用鼠标单击在图片框上绘制线条 ,但是当鼠标按钮向上时,绘制的线条消失。 我该如何解决?
private void GainBox_MouseDn(object sender, MouseEventArgs e)
{
mouse_dn = true;
}
private void GainBox_MouseMv(object sender, MouseEventArgs e)
{
//Line drawn from lookup table
if (mouse_dn)
{
img = new Bitmap(256, 256);
//Get the coordinates (x, y) for line from lookup table.
for (x = x1; x < x2; x++)
img.SetPixel(x, y, Color.Red);
//Same for y coordinate
}
GainBox.Refresh();
}
private void GainBox_MouseUp(object sender, MouseEventArgs e)
{
mouse_dn = false;
}
这是一个很小的完整程序,它确实基于点绘制线(在这种情况下,它跟随鼠标)。 我认为您可以将其改编成所需的内容。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Variable that will hold the point from which to draw the next line
Point latestPoint;
private void GainBox_MouseDown(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// Remember the location where the button was pressed
latestPoint = e.Location;
}
}
private void GainBox_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
using (Graphics g = GainBox.CreateGraphics())
{
// Draw next line and...
g.DrawLine(Pens.Red, latestPoint, e.Location);
// ... Remember the location
latestPoint = e.Location;
}
}
}
}
解决方案中的一个问题是您正在绘制临时位图,但是该位图中的图像永远不会传输到PictureBox
。 在此处介绍的解决方案中,不需要任何额外的位图。
gainbox.refresh()
应该保留在if (mouse_dn)
子句中。
使用图形对象绘制线条
例如
Graphics gfx = GainBox.CreateGraphics();
gfx.Drawline([Your Parameters here]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.