c# - 调整大小时清除表面
我正在尝试为 C#.Net 中的 Windows 窗体应用程序构建自己的自定义控件。目前,我使用绘制事件绘制一些矩形和其他图形元素。 当我现在调整应用程序表单的大小以适应桌面大小时,所有元素都会重新绘制(这正是我需要的行为),但旧的元素显示在背景中。
这就是我现在正在做的事情:
Pen penDefaultBorder = new Pen(Color.Wheat, 1);
int margin = 5;
private void CustomControl_Paint(object sender, PaintEventArgs e) {
CustomControl calendar = (CustomControl)sender;
Graphics graphics = e.Graphics;
graphics.Clear(Color.WhiteSmoke);
graphics.DrawRectangle(penDefaultBorder, margin, margin, calendar.Width - margin * 2, calendar.Height - margin * 2);
//...
}
graphics.Clear 和添加graphics.FillRectangle(...) 都不会从表面隐藏旧矩形。
有想法吗?谢谢大家。
I'm trying to build my own custom control for a windows forms application in C#.Net. Currently I paint some rectangles and other graphic elements using the paint event.
When I now resize the app form to fit the desktop size, all elements are repainted (which is exactly the behaviour I need) but the old one's are shown in the background.
Here's what I'm doing by now:
Pen penDefaultBorder = new Pen(Color.Wheat, 1);
int margin = 5;
private void CustomControl_Paint(object sender, PaintEventArgs e) {
CustomControl calendar = (CustomControl)sender;
Graphics graphics = e.Graphics;
graphics.Clear(Color.WhiteSmoke);
graphics.DrawRectangle(penDefaultBorder, margin, margin, calendar.Width - margin * 2, calendar.Height - margin * 2);
//...
}
Neither the graphics.Clear, nor adding a graphics.FillRectangle(...) will hide the old rectangle from the surface.
Ideas? Thank you all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
绘制事件通常不请求更新整个画布,只请求更新 PaintEventArgs 中指定的区域。我猜测发生的情况是只有画布新暴露的区域会在 PaintEventArgs 中传递。
这是您不应在 Paint 事件中进行任何渲染的原因之一。您应该渲染到屏幕外位图(缓冲区),并在 Paint 事件中从该缓冲区复制到控件的画布。
在此处或在 Google 上搜索“双缓冲”将为您提供该技术的许多示例。
Paint events usually don't request an update for the entire canvas, just the area specified in the PaintEventArgs. I'm guessing what's happening is that only the newly-exposed regions of the canvas are being passed in the PaintEventArgs.
This one of the reasons that you shouldn't do any rendering in the Paint event. You should render to an offscreen bitmap - a buffer - and copy from that buffer to the control's canvas in the Paint event.
Searching for "double buffering" here or on Google will give you many examples of the technique.
您是否尝试过
.Invalidate()
来导致表单重绘?Have you tried
.Invalidate()
to cause the form to redraw?