使用PixelShader效果帮助保存视觉文件 - WPF

时间:2009-06-04 17:48:48

标签: wpf effects

我正在尝试将wpf控件保存到文件中,但我正在对它应用PixelShader效果,当我尝试保存时,保存的图像完全是白色,黑色或红色...依赖于参数效果。

我在这里使用代码:WPF - Programmatic Binding on a BitmapEffect

我该如何妥善保存?

谢谢!

更新: 我正在使用的代码是:

        BitmapSource bitmap = preview.Source as BitmapImage;
        Rectangle r = new Rectangle();
        r.Fill = new ImageBrush(bitmap);
        r.Effect = effect;
        Size sz = new Size(bitmap.PixelWidth, bitmap.PixelHeight);
        r.Measure(sz);
        r.Arrange(new Rect(sz));
        var rtb = new RenderTargetBitmap(bitmap.PixelWidth, bitmap.PixelHeight, bitmap.DpiX, bitmap.DpiY, PixelFormats.Pbgra32);
        rtb.Render(r);

        PngBitmapEncoder png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(rtb));

        Stream stm = File.Create("new.png");
        png.Save(stm);
        stm.Close();

1 个答案:

答案 0 :(得分:0)

试试这段代码:

    /// <summary>
    /// Creates a screenshot of the given visual at the desired dots/inch (DPI).
    /// </summary>
    /// <param name="target">Visual component of which to capture as a screenshot.</param>
    /// <param name="dpiX">Resolution, in dots per inch, in the X axis. Typical value is 96.0</param>
    /// <param name="dpiY">Resolution, in dots per inch, in the Y axis. Typical value is 96.0</param>
    /// <returns>A BitmapSource of the given Visual at the requested DPI, or null if there was an error.</returns>       
    public static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
    {
        if (target == null)
        {
            return null;
        }

        RenderTargetBitmap rtb = null;

        try
        {
            // Get the actual size
            Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
            rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
                                          (int)(bounds.Height * dpiY / 96.0),
                                          dpiX,
                                          dpiY,
                                          PixelFormats.Pbgra32);

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                VisualBrush vb = new VisualBrush(target);
                ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
            }

            rtb.Render(dv);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine("Error capturing image: " + ex.Message);
            return null;
        }

        return rtb;
    }