开发者

How to render a bitmap from a WPF element that has a bitmap effect?

开发者 https://www.devze.com 2023-01-01 23:02 出处:网络
I\'m able to render a Visual to a bitmap fine with this code: Rect bounds = VisualTreeHelper.GetDescendantBounds(target);

I'm able to render a Visual to a bitmap fine with this code:

        Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
        RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

        DrawingVisual visual = new DrawingVisual();
        using (DrawingContext context = visual.RenderOpen())
        {
            VisualBrush brush = new VisualBrush(target);bounds.Value.Size));
            context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Value.Size));
        }
        renderBitmap.Render(visual);
        return renderBitmap;

The problem is that if the Visual has a bitmap effect like a drop shadow on it, then the resulting image is squished. It seems that its trying to fit the visual with the drop shadow into an image the size of the visual without开发者_JAVA技巧 the drop shadow.


In most cases (like drop shadow) the actual rendering of the effect falls outside of the bounds of the element itself. Relying on the ActualHeight and ActualWidth to size you image then causes the squeezing effect you're seeing. The best solution would be to use a parent container instead but that might require changes to your layout. You may also be able to calculate additional padding values to add to the element's size that will compensate for the effect rendering. It might be possible to derive those values by inspecting the properties of the Effect itself and will probably involve some trial and error too.


The effect has a set of padding properties and thes are used to set the size of rendering area used by the effect - see if these have been modified and if so adjust the size of the rendered visual. Have a look at RenderTargetBitmap - Visual vector to bitmap and the articles at WPF Workings

0

精彩评论

暂无评论...
验证码 换一张
取 消