我目前正在智能设备项目中开发弯曲进度条。我重写了 OnPaint 函数。
在Override OnPaint()函数中,我用深灰色绘制了弯曲的进度条,并用黄色绘制了进度条的一部分以反射(reflect)进度条的变化值(例如30%)。但是,当值连续变化时,我可以看到进度条的部分颜色变为黄色。然而,弯曲的进度条本身也被重新绘制。有谁知道如何在值发生变化时避免重绘原始弯曲进度条?这样当值改变时,它只将进度条的一部分重新绘制为黄色,而不是原来的进度条绘制为灰色。这是我在 OnPaint 函数中使用的代码。
protected override void OnPaint(PaintEventArgs e)
{
gx = e.Graphics;
// Draw the original curved progress bar
int intPosition1 = m_NumberOfSpoke;
for (int intCounter1 = 0; intCounter1 < m_NumberOfSpoke; intCounter1++)
{
intPosition1 = intPosition1 % m_NumberOfSpoke;
DrawLine(e.Graphics,
GetCoordinate(m_CenterPoint, m_InnerCircleRadius, m_Angles[intPosition1]),
GetCoordinate(m_CenterPoint, m_OuterCircleRadius, m_Angles[intPosition1]),
Color.DarkGray, m_SpokeThickness);
intPosition1++;
}
// Draw a part of the progress bar to reflect the changing current value(such as 30%)
int intPosition = CurrentValue;
for (int intCounter1 = 0; intCounter1 < CurrentValue; intCounter1++)
{
intPosition = intPosition % CurrentValue;
DrawLine(gx,
GetCoordinate(m_CenterPoint, m_InnerCircleRadius, m_Angles[intPosition]),
GetCoordinate(m_CenterPoint, m_OuterCircleRadius, m_Angles[intPosition]),
Color.Yellow, m_SpokeThickness);
intPosition++;
}
base.OnPaint(e);
}
我尝试使用Override OnBackgroundPaint来绘制原始的弯曲进度条作为背景,以避免在OnPaint中再次重绘它,但它不起作用。加载表单后我看不到任何东西。有什么想法吗?
感谢您提前提供的任何帮助。
问候
最佳答案
这是对实际屏幕的大量 DrawLine 调用,很可能会导致闪烁。您应该通过创建后台缓冲区来加倍缓冲区,在其中进行所有绘制,然后通过对 DrawBitmap
的一次调用将其传输到屏幕,如下所示:
protected override void OnPaint(PaintEventArgs e)
{
using(var buffer = new Bitmap(this.Width, this.Height))
using(var gx = Graphics.FromImage(buffer))
{
// for loops to draw to gx
....
e.Graphics.DrawBitmap(buffer, ...);
}
}
我也非常倾向于不完全执行上面的操作,而是缓存该缓冲区以防止每次调用时生成位图的垃圾。
Bitmap m_buffer;
Gramphic m_gx;
protected override void OnPaint(PaintEventArgs e)
{
if(m_buffer == null)
{
m_buffer = new Bitmap(this.Width, this.Height))
m_gx = Graphics.FromImage(buffer))
}
// clear the backbuffer with a FillRect
// for loops to draw to m_gx
....
e.Graphics.DrawBitmap(m_buffer, ...);
}
如果控件的灰色部分始终相同并执行“三重缓冲区”,我什至可能会更进一步,保留绘制灰色的图像的缓存版本,然后在 OnPaint 中,blit到图形中,绘制黄色,然后传输到屏幕。
Bitmap m_buffer;
Bitmap m_backimage;
Gramphic m_gx;
protected override void OnPaint(PaintEventArgs e)
{
if(m_buffer == null)
{
m_backimage = new Bitmap(this.Width, this.Height);
var g = Graphics.FromImage(m_backImage);
// for loop to draw the grey stuff to g
....
m_buffer = new Bitmap(this.Width, this.Height))
m_gx = Graphics.FromImage(buffer))
}
m_gx.DrawImage(m_backImage);
// for loop to draw *just the yellow* to m_gx
....
e.Graphics.DrawBitmap(m_buffer, ...);
}
您可能还需要重写 OnResize 和其他一些东西,再加上扩展 Dispose 来清理这些成员级 GDI 对象,但 perf 会更好,而且不会闪烁。
关于c# - winform 中的 OnPaint - .NET Compact Framework 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763682/