为什么 PictureBox 不画东西? [关闭]

问题描述 投票:0回答:2

当我在 VS 桌面应用程序中运行此代码时,当我用鼠标单击并拖动时,PictureBox 控件中没有任何内容。我没有更改 PictureBox 控件的任何属性。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private Bitmap _bitmap;
        private bool _isDrawing;
        private Point _startPoint;
        private Pen _pen;

        public Form1()
        {
            InitializeComponent();

            // Create a new bitmap with the same size as the PictureBox
            _bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);

            // Set the PictureBox's image to the bitmap
            pictureBox1.Image = _bitmap;

            // Set up the pen for drawing
            _pen = new Pen(Color.Black, 10);
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            _isDrawing = true;
            _startPoint = e.Location;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDrawing)
            {
                using (Graphics g = Graphics.FromImage(_bitmap))
                {
                    g.DrawLine(_pen, _startPoint, e.Location);
                }

                pictureBox1.Invalidate();

                _startPoint = e.Location;
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            _isDrawing = false;
            pictureBox1.Invalidate();
        }
    }
}
c# .net picturebox
2个回答
0
投票

事件处理程序未分配给 PictureBox 控件。从我发布的代码中看不出这一点。经过一些调试我意识到了。


-1
投票

调用invalidate调用清除图片框内容的方法。删除那条线,它应该能够在你的鼠标移动后画一条线。

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDrawing)
            {
                using (Graphics g = Graphics.FromImage(_bitmap))
                {
                    g.DrawLine(_pen, _startPoint, e.Location);
                }

                

                _startPoint = e.Location;
            }
        }

同样在您的 MouseUp 事件处理程序上,删除对 invalidate 的调用,因为一旦您释放鼠标按钮,绘图就会消失。当您想清除面板上的所有绘图或重置控件的图形上下文时,无效应该是理想的选择。

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            _isDrawing = false;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.