我有一个非常简单的代码来在我的用户控件上绘制网格(在调用基类OnBackgroundPaint之后):
private void DrawGrid(Graphics g)
{
Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);
for (int i = 0; i < this.Size.Width; i+=50)
{
g.DrawLine(p, new Point(i, this.Location.Y), new Point(i, this.Size.Height));
}
for (int i = 0; i < this.Size.Height; i += 50)
{
g.DrawLine(p, new Point(this.Location.X,i), new Point(this.Size.Width, i));
}
p.Dispose();
}当我将这个控件放在主窗体上并且不使用停靠时,它可以很好地调整大小。但是,当我将Dock属性设置为None以外的任何值时,在调整大小后,绘制的区域将被擦除,并且再也不会绘制。可能的原因是什么?
发布于 2018-01-14 20:03:14
这是因为在创建用户控件时,您必须从0,0位置开始,并且您想要在其上进行操作,则必须从0,0左上角位置开始,而不是在父级上重新分配用户控件
private void DrawGrid(Graphics g)
{
Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);
for (int i = 0; i < this.Size.Width; i+=50)
{
g.DrawLine(p, new Point(i, **0**), new Point(i, this.Size.Height));
}
for (int i = 0; i < this.Size.Height; i += 50)
{
g.DrawLine(p, new Point(**0**,i), new Point(this.Size.Width, i));
}
p.Dispose();
}此外,您还必须在控件构造函数中调用此函数:
this.SetStyle(ControlStyles.DoubleBuffer |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint,
true);
this.UpdateStyles();对用户控件绘图的调用tell在缓冲区中执行,完成后,结果将输出到屏幕上。双缓冲可防止因重绘控件而导致的闪烁。如果将DoubleBuffer设置为true,则还应将UserPaint和AllPaintingInWmPaint设置为true。如果为false,则不引发Paint事件。此样式仅适用于从Control派生的类。并且该控件忽略窗口消息WM_ERASEBKGND以减少闪烁。仅当UserPaint位设置为true时,才应应用此样式。
有关更多信息,您可以查看此链接:
https://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles(v=vs.110).aspx
https://stackoverflow.com/questions/48248833
复制相似问题