当我运行以下代码时,我在MyPictureBox对象中加载的图像会短暂闪烁,但随后该窗体将立即被标准Windows背景色覆盖。
我知道我确实缺少一些明显的东西。 (P.S.表单除了我添加的MyPictureBox之外没有其他控件。)
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Outlines {
public partial class Form1 : Form {
public MyPictureBox MPB;
public Form1() {
InitializeComponent();
MPB = new MyPictureBox("Benny.png");
this.Controls.Add(MPB);
}
private void Form1_Load(object sender, EventArgs e) {
Console.WriteLine("Form1:Load");
}
protected override void OnResizeEnd(EventArgs e) {
Console.WriteLine("Form1:ResizeEnd");
base.OnResizeEnd(e);
MPB.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
this.Invalidate(true);
}
protected override void OnClick(EventArgs e) {
Console.WriteLine("Form1:OnClick");
base.OnClick(e);
this.Invalidate(true);
}
protected override void OnPaint(PaintEventArgs e) {
Console.WriteLine("Form1:OnPaint");
base.OnPaint(e);
}
}
public class MyPictureBox : PictureBox {
private Bitmap _bitmap;
public MyPictureBox(string pathName) {
_bitmap = new Bitmap(pathName);
this.Size = new Size(500, 500);
this.Enabled = true;
this.Visible = true;
}
protected override void OnPaint(PaintEventArgs pe) {
Console.WriteLine("MPB:OnPaint");
base.OnPaint(pe);
var graphics = this.CreateGraphics();
graphics.Clear(Color.Gray);
if (_bitmap == null)
return;
graphics.DrawImage(_bitmap, new Point(0, 0));
graphics.Dispose();
}
protected override void OnResize(EventArgs e) {
Console.WriteLine("MPB:OnResize");
base.OnResize(e);
}
}
}
答案 0 :(得分:1)
不要在OnPaint方法内创建新的图形对象;使用PaintEvents参数中提供的参数。正如@Jimi指出的那样...
Control.CreateGraphics();用于特定的,已定义的情况(主要用于衡量事物)。不要使用它来绘制和存储它(一旦重新绘制控件,它将立即失效-这会不断发生)。始终使用提供的Graphics对象(作为PaintEventArgs)在重写的OnPaint()方法或Paint事件处理程序(或DrawItem和朋友)中进行绘制。