How make a Screenshot of UIElement in WPF

后端 未结 2 2008
甜味超标
甜味超标 2021-01-15 14:17

I have a problem with creating a screenshot of a scatterview. My screenshot always contains a black frame.

Here\'s my XAML-Code:



        
2条回答
  •  天涯浪人
    2021-01-15 14:39

    the following article has a workaround for your problem:

    Taking WPF “Screenshots”

    http://www.grumpydev.com/2009/01/03/taking-wpf-screenshots/

    ///
    /// Gets a JPG "screenshot" of the current UIElement
    ///
    /// UIElement to screenshot
    /// Scale to render the screenshot
    /// JPG Quality
    /// Byte array of JPG data
    public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
    {
        double actualHeight = source.RenderSize.Height;
        double actualWidth = source.RenderSize.Width;
    
        double renderHeight = actualHeight * scale;
        double renderWidth = actualWidth * scale;
    
        RenderTargetBitmap renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32);
        VisualBrush sourceBrush = new VisualBrush(source);
    
        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
    
        using (drawingContext)
        {
            drawingContext.PushTransform(new ScaleTransform(scale, scale));
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
        }
        renderTarget.Render(drawingVisual);
    
        JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
        jpgEncoder.QualityLevel = quality;
        jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
    
        Byte[] _imageArray;
    
        using (MemoryStream outputStream = new MemoryStream())
        {
            jpgEncoder.Save(outputStream);
            _imageArray = outputStream.ToArray();
        }
    
        return _imageArray;
    }
    

    hope this helps

提交回复
热议问题