加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从UIElement生成BitmapSource

发布时间:2020-12-16 01:30:35 所属栏目:百科 来源:网络整理
导读:我试图生成一个基于UIElement的BitmapFrame.这是我的功能: private BitmapFrame RenderToBitmap2(){ RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200,200,96,PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); Dr
我试图生成一个基于UIElement的BitmapFrame.这是我的功能:

private BitmapFrame RenderToBitmap2()
{
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200,200,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,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),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;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读