0

我想将 VisualBrush 保存到文件中。我尝试了许多不同的解决方案,但没有任何效果。我试图写一个简单的转换器:

public class BrushToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Brush)
        {
            var brush = (Brush)value;
            Size size = new Size(1000, 1000);
            if (parameter is Size)
                size = (Size)parameter;

            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
            if (brush is VisualBrush)
            {
                bitmap.Render(((VisualBrush)brush).Visual);
            }
            else
            {
                var drawingVisual = new DrawingVisual();
                using (DrawingContext context = drawingVisual.RenderOpen())
                {
                    context.DrawRectangle(brush, null, new Rect(0, 0, bitmap.Width, bitmap.Height));
                }

                bitmap.Render(drawingVisual);
            }

            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(File.OpenWrite(ViewModel.MainViewModel.Random.Next().ToString() + ".png"));

            return (ImageSource)bitmap;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

总而言之,结果是黑色图像。但是,如果我将源画笔更改为 Brushes.Red 之类的东西,则结果是红色图像。所以我猜想对位图的渲染失败,但保存到文件是有效的。

有谁知道我做错了什么?

4

0 回答 0