开发者

C# WinForms problem with draw image

class OriginalImage: Form { private Image image; private PictureBox pb;

    public OriginalImage()
    {
        pb = new PictureBox {SizeMode = PictureBoxSizeMode.CenterImage};
        pb.SizeMode = PictureBoxSizeMode.StretchImage;

        Controls.Add(pb);

        image = Image.FromFile(@"Image/original.jpg");

        this.Width = image.Width;
        this.Height = image.Height;

        this.Text = "Original image";
        this.Paint += new PaintEventHandler(Drawer);
    }

    publ开发者_StackOverflowic virtual void Drawer(object source, PaintEventArgs e)
    {
        Graphics g = pb.CreateGraphics();
        g.DrawImage(image,0,0);
    }

I call this create object OriginalImage in other form on button click, but image is not draw? Where is problem?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var oi = new OriginalImage();
        oi.Show();
    }
}


You're creating a PictureBox and adding it to your controls, but you never actually use it (you're drawing the image manually in the Paint event). Why? This control is likely obscuring the drawing area of the form, as any controls go on top of whatever you draw in the Paint event.

In addition, you're getting the Graphics object by calling CreateGraphics on the PictureBox rather than the Form itself. This is wrong, as the PictureBox's Paint event will fire after this code, erasing whatever you draw.

I would recommend changing your OriginalForm code to the following:

class OriginalImage: Form
{
    private Image image;
    private PictureBox pb;

    public OriginalImage()
    {
        pb = new PictureBox();
        pb.SizeMode = PictureBoxSizeMode.StretchImage;

        pb.Dock = DockStyle.Fill; // this will make the PictureBox occupy the
                                  // whole form

        Controls.Add(pb);

        image = Image.FromFile(@"Image/original.jpg");

        this.ClientSize = new Size(image.Width, image.Height); // this allows you to
                                                               // size the form while
                                                               // accounting for the
                                                               // border

        this.Text = "Original image";

        pb.Image = image; // use this instead of drawing it yourself.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜