C# 最近邻位图导致撕裂

C# 最近邻位图导致撕裂,c#,wpf,bitmap,C#,Wpf,Bitmap,我已经创建了一个生成代码39条形码的测试应用程序。问题是当我在屏幕上显示条形码时,它要么模糊,要么被撕破。如果我使用任何位图缩放模式,而不是最近邻,我会得到模糊的条形码。当我使用NearestNeighbor时,我会得到对角线斜线,如下所示。对角线仅在调整窗口大小时出现。(如果我停在正确的位置,它会留在那里。)图像本身不会改变大小,而是在我调整窗口大小时在屏幕上移动 我也尝试过使用RenderOptions.EdgeMode=“Aliased”,但似乎没有任何效果 撕裂/模糊/正确 WPF示

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

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

撕裂/模糊/正确

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>
示例生成代码:

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”
可以解决此问题

[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;
}