Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

c# - PictureBox PaintEvent with other method

There is only one picturebox in my form and I want to drawcircle with a method on this picturebox but I cant do that and not working.The method is:

private Bitmap Circle()
    {
        Bitmap bmp;
        Graphics gfx;
        SolidBrush firca_dis=new SolidBrush(Color.FromArgb(192,0,192));

            bmp = new Bitmap(40, 40);
            gfx = Graphics.FromImage(bmp);
            gfx.FillRectangle(firca_dis, 0, 0, 40, 40);

        return bmp;
    }

Picturebox

 private void pictureBox2_Paint(object sender, PaintEventArgs e)
    {
        Graphics gfx= Graphics.FromImage(Circle());
        gfx=e.Graphics;
    }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to decide what you want to do:

  • Draw into the Image or
  • draw onto the Control?

Your code is a mix of both, which is why it doesn't work.

Here is how to draw onto the Control:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawEllipse(Pens.Red, new Rectangle(3, 4, 44, 44));
    ..
}

Here is how to draw into the Image of the PictureBox:

void drawIntoImage()
{
    using (Graphics G = Graphics.FromImage(pictureBox1.Image))
    {
        G.DrawEllipse(Pens.Orange, new Rectangle(13, 14, 44, 44));
        ..
    }
    // when done with all drawing you can enforce the display update by calling:
    pictureBox1.Refresh();
}

Both ways to draw are persistent. The latter changes to pixels of the Image, the former doesn't.

So if the pixels are drawn into the Image and you zoom, stretch or shift the Image the pixel will go with it. Pixels drawn onto the Top of the PictureBox control won't do that!

Of course for both ways to draw, you can alter all the usual parts like the drawing command, maybe add a FillEllipse before the DrawEllipse, the Pens and Brushes with their Brush type and Colors and the dimensions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...