c# - VisualStyleRenderer 到位图

标签 c# gdi+

我需要通过 VisualStyleRenderer 绘制不同的进度条。如果我使用 OnPaint 方法的 Graphics 一切正常。但是因为我想把它保存在硬盘中,所以我需要在 Bitmap 对象中渲染进度条,然后保存它。

这是示例代码

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.DrawImage(RenderProgressbarImage(), new Point(5, 5));

    //following code works good
    progressRenderer.SetParameters("PROGRESS", 11, 2);
    progressRenderer.DrawBackground(e.Graphics, new Rectangle(125, 5, 100, 13));
}
VisualStyleRenderer progressRenderer = new VisualStyleRenderer(VisualStyleElement.ProgressBar.Bar.Normal);
Bitmap RenderProgressbarImage()
{
    Bitmap bmp = new Bitmap(100, 13);
    using (Graphics g = Graphics.FromImage((Image)bmp))
    {
        progressRenderer.SetParameters("PROGRESS", 11, 2);
        progressRenderer.DrawBackground(g, new Rectangle(0, 0, bmp.Width, bmp.Height));                
    }
    return bmp;
}

但是如果我在 Bitmap 中绘制它,它有黑色的角而不是透明的。但是,如果它使用 OnPaintGraphics,一切都很好。

screenshot

最佳答案

使用 Bitmap,您将按照自己的方式使用 GDI+ 生成一个矩形对象。

Creating an Image with Rounded Corners可能会帮助您根据需要创建圆形位图图像。

编辑 - 修改了 RenderProgressbarImage 以将 Graphics 对象作为输入

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.DrawImage(RenderProgressbarImage(e.Graphics), new Point(5, 5));

    //Test to Check for Output
    RenderProgressbarImage(e.Graphics).Save(@"C:\Bitmap.bmp");;

    //following code works good
    progressRenderer.SetParameters("PROGRESS", 11, 2);
    progressRenderer.DrawBackground(e.Graphics, new Rectangle(125, 5, 100, 13));
}
Bitmap RenderProgressbarImage(Graphics g)
{
    Bitmap bmp = new Bitmap(100, 13, g);
    progressRenderer.SetParameters("PROGRESS", 11, 2);
    progressRenderer.DrawBackground(g, new Rectangle(0, 0, bmp.Width, bmp.Height));

    return bmp;
}

Edit2:修改以根据下面 OP 的评论简化解决方案

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Bitmap bmp = new Bitmap(100, 13, e.Graphics);
    bmp.Save(<SomefilePath.png>);

    //following code works good
    progressRenderer.SetParameters("PROGRESS", 11, 2);
    progressRenderer.DrawBackground(e.Graphics, new Rectangle(125, 5, 100, 13));
}

注意事项:在 OnPaint 事件中保存 Bitmap 将对渲染性能产生一定的影响。也许只是在你的类中更新一个 Bitmap 变量并从不同的 Thread/一些 Timer/定期保存 Bitmap ETC。;这完全取决于您的需求。

关于c# - VisualStyleRenderer 到位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16030798/

相关文章:

c# - 如何在Word中的表格单元格中插入换行符?

c# - 从 MemoryStream() 反序列化

c# - 如何更改 GDI+ LinearGradientBrush 的颜色?

c++ - GDI+ 对象的 std::make_unique

c++ - 从 X : The readable size is Y bytes, 读取无效数据但可能读取 Z 字节

c# - 我如何计算和创建三角形的位置?

c# - 快速可查询的对象集合

c# - Windows Phone 8 蓝牙错误 HRESULT : 0x8007271D

C++ gdi 图像数组

c# - 在收到所有数据之前,如何开始显示隔行扫描的 PNG?