c# - 从 UIElement 生成 BitmapSource

标签 c# wpf bitmap drawing uielement

我正在尝试生成一个基于 UIElementBitmapFrame。这是我的功能:

private BitmapFrame RenderToBitmap2()
{
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);

    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();
    VisualBrush aVisualBrush = new VisualBrush(GenerateTestStackPanel());
    drawingContext.DrawRectangle(aVisualBrush, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150)));

    drawingContext.Close();

    renderBitmap.Render(drawingVisual);

    return BitmapFrame.Create(renderBitmap);
}

出于测试和调试的目的,我使用了一个额外的函数来创建一个简单的 StackFrame,应该创建一个可以表示的有效可视元素:

private StackPanel GenerateTestStackPanel()
{
    // Create a red Ellipse.
    Ellipse myEllipse = new Ellipse();

    myEllipse.Fill = Brushes.Green;
    myEllipse.StrokeThickness = 2;
    myEllipse.Stroke = Brushes.Black;

    // Set the width and height of the Ellipse.
    myEllipse.Width = 200;
    myEllipse.Height = 200;
    // Add the Ellipse to the StackPanel.
    StackPanel myStackPanel = new StackPanel();
    myStackPanel.Children.Add(myEllipse);
    return myStackPanel;
}

出于某种原因,VisualBrush 未在 DrawRetangle(...) 函数中呈现。我可以看到绿色边框,但没有别的。此外,如果我用标准画笔换掉 VisualBrush,效果会很好:

drawingContext.DrawRectangle(Brushes.Plum, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150)));

提前致谢!

最佳答案

看看这个从 UIElement 创建 BitmapSource 的替代方法:

MSDN Thread

我也一直在尝试让 VisualBrush 正常工作,但运气不佳,这让我想到了这个话题。

public static BitmapSource CreateBitmapSourceFromVisual(
    Double width,
    Double height,
    Visual visualToRender,
    Boolean undoTransformation)
    {
        if (visualToRender == null)
        {
            return null;
        }
        RenderTargetBitmap bmp = new RenderTargetBitmap((Int32)Math.Ceiling(width),
            (Int32)Math.Ceiling(height), 96, 96, PixelFormats.Pbgra32);

        if (undoTransformation)
        {
            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext dc = dv.RenderOpen())
            {
                VisualBrush vb = new VisualBrush(visualToRender);
                dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
            }
            bmp.Render(dv);
        }
        else
        {
            bmp.Render(visualToRender);
        }
      return bmp;
    }

关于c# - 从 UIElement 生成 BitmapSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831860/

相关文章:

c# - 记录 WPF 项目时的最佳实践

c# - 繁忙指示器未显示在 wpf 窗口中

c# - 在位图周围绘制边框

delphi - 以编程方式将颜色从加载的位图逐像素交换为红色、绿色、蓝色或灰色

image - 在黑莓中使用 Bitmap 还是 EncodedImage 更好?

c# - ConfUserEx 从混淆中排除命名空间

c# - MySQL Connector/NET SSL 关闭服务器

.net - 从父控件设置 WPF 嵌套控件属性

wpf - 将数据传递给 mvvm 用户控件

c# - 是否可以在 app.config 中的 "supportedRuntime"中指定 .NET 服务包?