当使用不同于96 DPI的RenderTargetBitmap时,WPF禁用Text的抗锯齿

时间:2017-02-01 08:42:11

标签: c# wpf

经过数小时的反复试验,我需要你的帮助!

我正在尝试创建一个代表WPF控件的图像文件,但我需要所有文本/图形都是别名(即不是抗锯齿)。我需要使用高于默认值96.0的DPI创建图像,因为文本质量不足以满足我在该级别的需要。

每当我使用96.0以外的DPI使用RenderTargetBitmap渲染图像时,文本都会消除锯齿,我无法阻止它。以96.0 DPI渲染文本没有消除锯齿并正确显示 - 但质量水平不够。

渲染代码:

namespace TestRenderBitmap
{
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    public partial class RenderTargetBitmapTestWindow
    {
        public RenderTargetBitmapTestWindow()
        {
            InitializeComponent();
        }

        private void cmdRender_Click(object sender, RoutedEventArgs e)
        {
            var requiredDpi = 96.0;
            SaveToPngStream(controlToRender, requiredDpi);
        }

        public void SaveToPngStream(FrameworkElement control, double targetDpi)
        {
            var encoder = EncodeControlToImage(control, targetDpi);
            using (var filestream = new FileStream("output.png", FileMode.Create))
                encoder.Save(filestream);
        }

        private BitmapEncoder EncodeControlToImage(FrameworkElement control, double targetDpi)
        {
            var bmp = GetBitmapFromControl(control, targetDpi);
            var encoder = new PngBitmapEncoder { Interlace = PngInterlaceOption.Off };

            encoder.Frames.Add(BitmapFrame.Create(bmp));
            return encoder;
        }

        private RenderTargetBitmap GetBitmapFromControl(FrameworkElement control, double targetDpi)
        {
            const double screenDpi = 96d;

            var height = control.ActualHeight; 
            var width = control.ActualWidth;
            var dv = new DrawingVisual();

            using (var ctx = dv.RenderOpen())
            {
                var br = new VisualBrush { Visual = control };

                ctx.DrawRectangle(br, null, new Rect(0, 0, width, height));
            }
            var bmp = new RenderTargetBitmap((int)(width / screenDpi * targetDpi), (int)(height / screenDpi * targetDpi),
                targetDpi, targetDpi, PixelFormats.Default);
            bmp.Render(dv);
            return bmp;
        }
    }
}

XAML代码是:

<Grid>
    <Grid TextOptions.TextRenderingMode="Aliased" TextOptions.TextFormattingMode="Display" x:Name="controlToRender" HorizontalAlignment="Left" VerticalAlignment="Top" Background="White">
        <TextBlock VerticalAlignment="Center" TextWrapping="Wrap" HorizontalAlignment="Center" FontSize="10.667" FontFamily="Arial" Margin="33,41,55,56" Text="Hello World" />
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="100" Margin="22,26,0,0" VerticalAlignment="Top" Width="107"/>
    </Grid>

    <Button x:Name="cmdRender" Content="Render" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="75" Click="cmdRender_Click" Margin="0,0,10,10" />
</Grid>

在96.0 DPI我得到一个如下图像(缩放): 96DPI Image

在192DPI时此图像如下所示:192DPI Image

0 个答案:

没有答案