2010-03-29 85 views
1

class OriginalImage:Form { private image image; private PictureBox pb;C#WinForms问题与绘制图像

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); 
    } 

    public virtual void Drawer(object source, PaintEventArgs e) 
    { 
     Graphics g = pb.CreateGraphics(); 
     g.DrawImage(image,0,0); 
    } 

我把这个创建对象按照其他形式称为创建对象OriginalImage,但是图像没有被绘制?问题在哪里?

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

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

为什么你是从形式来实现的原因吗?而不只是创建一个图像,并将其添加到当前的形式? – 2010-03-29 13:53:36

+0

这听起来像他想以一种新形式展示图像...。 – 2010-03-29 13:56:36

回答

2

你正在创建一个PictureBox并将其添加到您的控件,但你从来没有真正使用它(你手工绘制的图像中的Paint事件)。为什么?此控件可能会遮住表单的绘图区域,因为任何控件都会在您在Paint事件中绘制的任何控件之上进行。

另外,您通过PictureBox而不是Form本身调用CreateGraphics得到Graphics对象。这是错误的,因为PictureBox的Paint事件将在之后触发,这会擦除您绘制的任何内容。

我会建议您更改OriginalForm代码如下:

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. 
    } 
}