【问题标题】:Assign Drawing to pictureBox将绘图分配给图片框
【发布时间】:2014-12-27 15:06:21
【问题描述】:

我有一个每 500 毫秒调用一次的函数,它应该删除 PictureBox 中包含的旧绘图并用新绘图替换它

public override void onUpdate()
        {
            pictureBox.Image = null;
            Graphics g = pictureBox.CreateGraphics();
            Pen p = new Pen(System.Drawing.Color.Blue, 3);
            Random rnd = new Random();
            int randomInt = rnd.Next(0, 11);
            g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
            p.Dispose();
            g.Dispose();
            return;
        }

不起作用(屏幕上什么也没有出现),除非在调试时.. 而当我这样做时:

 public override void onUpdate()
        {
            Graphics g = pictureBox.CreateGraphics();
            Pen p = new Pen(System.Drawing.Color.Blue, 3);
            Random rnd = new Random();
            int randomInt = rnd.Next(0, 11);
            g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
            p.Dispose();
            g.Dispose();
            System.Threading.Thread.Sleep(5000);
            pictureBox.Image = null;
            return;
        }

圆圈每 5 秒绘制一次,然后消失 500 毫秒

第二个对我来说是逻辑,但我不明白为什么第一个不能按我想要的方式工作。如果我删除“pictureBox.Image = null;”行,旧的圆圈没有被删除。

我能做什么,每次调用 onUpdate() 时都重新绘制圆圈,并让它一直保持到下一次调用它?

【问题讨论】:

  • 您应该使用绘图事件中的 Graphic 对象,而不是 CreateGraphics。您还应该使用计时器,而不是循环(我猜这就是您调用 onUpdate 的方式)。在tick 事件中,调用pictureBox.Invalidate();,在paint 事件中,绘制你的图片。无需设置 Image 属性。

标签: c# picturebox system.drawing


【解决方案1】:

Winforms GDI+ 已经有一段时间了...

新方法:制作一个用户控件并在里面输入下面的代码,然后用新控件替换您的图片框(您必须编译一次,以便它在您的工具箱中)和您的代码,只需调用 UpdateCircle 方法新控件:

 public partial class CircleControl : UserControl
{
    private Random rnd = new Random();
    Pen p = new Pen(Color.Blue, 3);

    public CircleControl()
    {
        InitializeComponent();
        this.Paint += CircleControl_Paint;

    }

    public void UpdateCircle() 
    {
        this.Invalidate();
    }

    void CircleControl_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(Color.White);
        int randomInt = rnd.Next(0, 11);
        e.Graphics.DrawEllipse(p, new Rectangle(new Point(0, randomInt), this.Size));
    }
}

【讨论】:

  • 我不明白你的意思,但是这个不起作用:Graphics graphics = pictureBox.CreateGraphics();笔 p = new Pen(System.Drawing.Color.Blue, 1); graphics.DrawEllipse(p, new Rectangle(new Point(0,new Random().Next(0, 11)), new Size(pictureBox.Size.Width-20, pictureBox.Size.Height-20))); p.Dispose(); graphics.Dispose();位图 bitMap = Bitmap.FromHbitmap(graphics.GetHdc());图片框.Image = 位图;
猜你喜欢
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2013-01-15
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多