Painting to panel after .Update() call

2019-03-03 10:27发布

问题:

I have a problem when trying to draw to a panel immediatly after calling a panel.Update(); Here's the code:

    public void AddAndDraw(double X, double Y){
        AddPoint (X, Y);
        bool invalidated = false;

        if (X > _master.xMaxRange) {
            _master.Update ();
            invalidated = true;
        }
        if (Y > _master.yMaxRange) {
            _master.Update ();
            invalidated = true;
        }

        if (!invalidated) {
            _master.UpdateGraph (this);
        } else {
            _master.PaintContent ();
        }
    }

When running this problem I only see the cleared panel and not he content I'm trying to paint in the .PaintContent()-method. I've already tried using .Invalidate() and .Refresh() on the panel instead of .Update()

Any suggestions on how to fix this?

回答1:

It seems your situation calls for a PictureBox.

PBs are interesting here because they have three layers they can display:

  • They have a BackgroundImage property
  • They have an Image property
  • And as most controls they have a surface you can draw on in the Paint event

As you need a fixed axis, and graph that is not changing all the time and a point you want to update often PB seems to be made for you!

Call the functions as needed and when the point has changed call Invalidate() on your PictureBox!

Bitmap GraphBackground = null;
Bitmap GraphImage = null;
Point aPoint = Point.Empty;

private void Form1_Load(object sender, EventArgs e)
{
    PictureBox Graph = pictureBox1;  // short reference, optional

    GraphBackground = new Bitmap(Graph.ClientSize.Width, Graph.ClientSize.Height);
    GraphImage = new Bitmap(Graph.ClientSize.Width, Graph.ClientSize.Height);

    // intial set up, repeat as needed!
    Graph.BackgroundImage = DrawBackground(GraphBackground);
    Graph.Image = DrawGraph(GraphImage);
}

Bitmap DrawBackground(Bitmap bmp)
{
    using (Graphics G = Graphics.FromImage(bmp) )
    {
        // my little axis code..
        Point c = new Point(bmp.Width / 2, bmp.Height / 2);
        G.DrawLine(Pens.DarkSlateGray, 0, c.Y, bmp.Width, c.Y);
        G.DrawLine(Pens.DarkSlateGray, c.X, 0, c.X, bmp.Height);
        G.DrawString("0", Font, Brushes.Black, c);
    }
    return bmp;
}

Bitmap DrawGraph(Bitmap bmp)
{
    using (Graphics G = Graphics.FromImage(bmp))
    {
        // do your drawing here

    }

    return bmp;
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    // make it as fat as you like ;-)
    e.Graphics.FillEllipse(Brushes.Red, aPoint.X - 3, aPoint.Y - 3, 7, 7);
}


标签: c# panel paint