class OriginalImage:Form { 私人图片图片; 私人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);
}
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 :(得分:2)
您正在创建PictureBox
并将其添加到控件中,但您实际上从未使用它(您在Paint
事件中手动绘制图像)。为什么?此控件可能会遮盖表单的绘图区域,因为任何控件都会覆盖您在Paint
事件中绘制的任何内容。
此外,您通过调用Graphics
上的CreateGraphics
而不是PictureBox
本身来获取Form
个对象。这是错误的,因为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.
}
}