c# - 具有最近邻居的位图会导致撕裂

标签 c# wpf bitmap

我创建了一个生成 Code 39 条形码的测试应用程序。问题是,当我在屏幕上显示条形码时,它要么模糊不清,要么被撕裂。如果我使用 NearestNeighbor 以外的任何 BitmapScalingMode,我会得到模糊的条形码。当我使用 NearestNeighbor 时,我得到如下所示的斜线。对角线仅在我调整窗口大小时出现。 (如果我停在正确的位置,它就会停留在那里。)图像本身不会改变大小,而是在我调整窗口大小时在屏幕上移动。

我也尝试过使用 RenderOptions.EdgeMode="Aliased",但它似乎没有任何效果......

撕裂/模糊/正确

Torn Barcode Blurred Barcode Correct Barcode

WPF 示例代码:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,50,0,0">
    <Image x:Name="imgBarcode" Stretch="Fill" RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.EdgeMode="Aliased" />
</Border>

图像生成:

imgBarcode.Source = loadBitmap(c.Generate(barcodeText.Text));
imgBarcode.Width = c.GetWidth();
imgBarcode.Height = c.GetHeight();

示例生成代码:

Bitmap bmp = new Bitmap(width, height);
using (Graphics gfx = Graphics.FromImage(bmp))
using (SolidBrush black = new SolidBrush(Color.Black))
using (SolidBrush white = new SolidBrush(Color.White))
{
    // Start the barcode:
    addBar(gfx, black, white, '*');

    foreach (char c in barcode)
    {
        addCharacter(gfx, black, white, c);
    }

    // End the barcode:
    addBar(gfx, black, white, '*');
}

示例矩形添加:

g.FillRectangle(white, left, top, narrow, height);
left += narrow;

加载取自另一个 StackOverflow 问题的位图:

[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);

public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
    IntPtr ip = source.GetHbitmap();
    BitmapSource bs = null;
    try
    {
        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
           IntPtr.Zero, Int32Rect.Empty,
           System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
        DeleteObject(ip);
    }

    return bs;
}

最佳答案

在主窗口上设置 UseLayoutRounding="True" 应该可以解决这个问题。

关于c# - 具有最近邻居的位图会导致撕裂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481954/

相关文章:

c# - 移动到圆形区域,然后捕捉到网格?

c# - 如何添加(连接)两个 Google.Protobuf.ByteStrings? C#

c# - 为什么公共(public)类不能从不太可见的类继承?

c - 在 WPF tabControl 中,如何从对象类型中动态选择标签页?

java - 从输入流读取

C# 动态关键字——运行时惩罚?

wpf - 扩展 UserControl WPF 的自定义控件中的 TextChanged 或 ContentChanged 事件

c# - CartesianChart 上未显示 LiveCharts SeriesCollection

c - 如何表示二进制透明度?

C++ raytracer 不将值写入位图