如何解决面板背景在滚动过程中不刷新C#/ VB.net
我在C#和VB.net中有一个奇怪的滚动/背景错误。 创建面板并使用“自动滚动”时,滚动过程中不会更新背景。 最后,它看起来真的很奇怪(视频:https://youtu.be/0vaO-zmWFmk) 我尝试使用TabControl进行同样的操作,并且背景像应该滚动的那样。 我尝试了外部滚动条,同样的事情发生了。我也尝试过VB.net。 我认为这是Visual Studios的错误,如果有人可以帮助我,我将不胜感激 谢谢LG!
解决方法
如果您希望图像通过滚动条滚动,则只需扩展Panel
并覆盖OnPaintBackground
即可轻松实现。
请记住,如果要执行此操作,则必须使控件DoubleBuffered
(在下面的代码中为您完成了此操作)。
在此示例中,我添加了“平铺”选项。因此,您可以使用一个大图像,也可以使用无缝平铺并将其平铺(通过BackgroundImageLayout
属性进行设置。所有其他选项都将绘制相同的图像)。
C#
using System.Drawing;
using System.Windows.Forms;
public class PanelEx : Panel
{
public PanelEx()
{
DoubleBuffered = true;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (BackgroundImage != null)
{
if (ImageLayout.Tile == BackgroundImageLayout)
{
for (int x = 0; x <= DisplayRectangle.Width;
x += BackgroundImage.Width)
{
for (int y = 0; y <= DisplayRectangle.Height;
y += BackgroundImage.Height)
{
e.Graphics.DrawImage(BackgroundImage,new Point(x - HorizontalScroll.Value,y - VerticalScroll.Value));
}
}
}
else
{
e.Graphics.DrawImage(BackgroundImage,new Point(-HorizontalScroll.Value,-VerticalScroll.Value));
}
}
else
{
base.OnPaintBackground(e);
}
}
}
使用方法
- 右键单击您的项目,然后在菜单中选择
Add
,然后选择Class
。将类别命名为PanelEx.cs
- 将上面的代码复制并粘贴到该类文件中。
- 在具有要修改的面板的表单中,进入设计器文件(请参见下图)
- 将
System.Windows.Forms.Panel();
的所有实例更改为PanelEx();
- 保存,进行完全重建并运行。
VB.NET
Public Class PanelEx
Inherits Panel
Public Sub New()
DoubleBuffered = True
End Sub
Protected Overrides Sub OnPaintBackground(e As PaintEventArgs)
If Not BackgroundImage Is Nothing Then
If BackgroundImageLayout = ImageLayout.Tile Then
Dim x As Integer,y As Integer
While x <= DisplayRectangle.Width
y = 0
While y <= DisplayRectangle.Height
e.Graphics.DrawImage(
BackgroundImage,New Point(x - HorizontalScroll.Value,y - VerticalScroll.Value))
y += BackgroundImage.Height
End While
x += BackgroundImage.Width
End While
Else
e.Graphics.DrawImage(BackgroundImage,New Point(-HorizontalScroll.Value,-VerticalScroll.Value))
End If
Else
MyBase.OnPaintBackground(e)
End If
End Sub
End Class
使用方法
- 右键单击您的项目,然后在菜单中选择
Add
,然后选择Class
。将类别命名为PanelEx.vb
- 将上面的代码复制并粘贴到该类文件中。
- 在具有要修改的面板的表单中,进入设计器文件(请参见下图)
- 将
Panel
的所有实例更改为PanelEx
- 保存,进行完全重建并运行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。