如何在图片框中绘制图纸

Bin*_*inu 7 c# picturebox

在图片中绘制图片使用c#拖动鼠标

Mus*_*sis 21

将PictureBox放在窗体上,并将其BackColor设置为White.然后将此代码添加到您的表单中(您必须实际连接下面的鼠标事件,即您不能将此代码复制并粘贴到您的表单中):

private Point? _Previous = null;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    _Previous = e.Location;
    pictureBox1_MouseMove(sender, e);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (_Previous != null)
    {
        if (pictureBox1.Image == null)
        {
            Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
            }
            pictureBox1.Image = bmp;
        }
        using (Graphics g = Graphics.FromImage(pictureBox1.Image))
        {
            g.DrawLine(Pens.Black, _Previous.Value, e.Location);
        }
        pictureBox1.Invalidate();
        _Previous = e.Location;
    }
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    _Previous = null;
}
Run Code Online (Sandbox Code Playgroud)

然后抽离!

如果您愿意,可以通过设置Graphics对象的SmoothingMode属性来稍微提高绘制图像的质量.

更新: .Net CF没有Pens集合,MoustEventArgs也没有Location,所以这里是一个CF友好的版本:

private Point? _Previous = null;
private Pen _Pen = new Pen(Color.Black);
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    _Previous = new Point(e.X, e.Y);
    pictureBox1_MouseMove(sender, e);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (_Previous != null)
    {
        if (pictureBox1.Image == null)
        {
            Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
            }
            pictureBox1.Image = bmp;
        }
        using (Graphics g = Graphics.FromImage(pictureBox1.Image))
        {
            g.DrawLine(_Pen, _Previous.Value.X, _Previous.Value.Y, e.X, e.Y);
        }
        pictureBox1.Invalidate();
        _Previous = new Point(e.X, e.Y);
    }
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    _Previous = null;
}
Run Code Online (Sandbox Code Playgroud)


Fir*_*roz 0

您可以通过捕获图片框的 mousemove 事件然后从图片框获取图形来实现,如 。

图形 g= pictureBox.CreateGraphics(); 然后你可以使用这个图形对象绘制任何你想要绘制的东西