Generate BitmapSource from UIElement

前端 未结 2 1976
孤城傲影
孤城傲影 2021-02-11 00:36

I am attempting to generate a BitmapFrame that is based on a UIElement. Here is my function:

private BitmapFrame RenderToBitmap2()
{
           


        
2条回答
  •  孤独总比滥情好
    2021-02-11 01:05

    Take a look at this for an alternate way to create a BitmapSource from a UIElement:

    MSDN Thread

    I have also been trying to get the VisualBrush to work without any luck which brought me to this thread.

    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;
        }
    

提交回复
热议问题