展开 Winform 窗口时,虚线矩形显示为实线
我在自定义绘制虚线矩形时遇到 GDI+ 问题。
当窗口大小增加或向上/向下滚动时,虚线矩形的垂直部分显示为实线、连续线。 更快地移动鼠标会导致实体部分越来越少。 奇怪的是,水平线并没有表现出这种行为,而是按预期出现。
到目前为止,两个非最佳解决方案是设置 ResizeRedraw = true
或在 OnResize()
和 OnScroll 期间调用
。 我当然想避免这种情况,因为我真正绘制的内容更加复杂,这些缓慢的调用破坏了流畅的体验。 我也尝试过仅使新显示的区域无效,但无济于事 - 只有完整的无效似乎才有效。Invalidate()
()
有关如何解决这个问题的任何指示吗?
演示代码:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class Form1 : Form
{
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.ClientSize = new System.Drawing.Size(472, 349);
DoubleBuffered = true;
//ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int dimensions = 70;
using ( Pen pen = new Pen(Color.Gray) )
{
pen.DashStyle = DashStyle.Dash;
for ( int x = 0; x < 20; ++x )
{
for ( int y = 0; y < 20; ++y )
{
Rectangle rect = new Rectangle(x * dimensions, y * dimensions, dimensions, dimensions);
e.Graphics.DrawRectangle(pen, rect);
}
}
}
}
}
I'm experiencing an issue with GDI+ while custom painting dashed rectangles.
The vertical portion of dashed rectangles appear as solid, continuous lines when the window size is increased or when scrolling up/down. Moving the mouse faster results in fewer and fewer solid sections. Curiously the horizontal lines do not exhibit this behaviour and appear as expected.
So far two non-optimal solutions have been to set ResizeRedraw = true
or to call Invalidate()
during OnResize()
and OnScroll()
. I'd of course like to avoid this as what I am really drawing is more complex and these slow calls destroy the fluid experience. I've also tried invalidating only the newly shown area to no avail - only a full Invalidate seems to work.
Any pointers on how to work this out?
Demo code:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class Form1 : Form
{
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.ClientSize = new System.Drawing.Size(472, 349);
DoubleBuffered = true;
//ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int dimensions = 70;
using ( Pen pen = new Pen(Color.Gray) )
{
pen.DashStyle = DashStyle.Dash;
for ( int x = 0; x < 20; ++x )
{
for ( int y = 0; y < 20; ++y )
{
Rectangle rect = new Rectangle(x * dimensions, y * dimensions, dimensions, dimensions);
e.Graphics.DrawRectangle(pen, rect);
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为有两个问题:窗口边缘似乎有一个区域没有正确绘制矩形; 并且您正在将矩形绘制在彼此之上,因此虚线将无法正常工作。
将 OnPaint 循环替换为以下内容:
I think there are two problems: there appears to be an area at the edge of the window where rectangles aren't drawn correctly; and you're drawing the rectangles over each other, so the dashing won't work properly.
Replace your OnPaint loop with the following: