.NET Core System.Drawing.Common 中文亂碼的坑

最近在寫一個漢字取點陣的程序,最開始是在win環境下運行的,沒發現什麼異常,而後今天把程序放在centos 下後發現英文正常,中文徹底變成兩位的字了,最開始是字體的緣由git

在把宋體等安裝到centos 後發現中文出來了 但徹底變了另外的字,而後使用第三方的ZKWeb.System.Drawing 運行程序,發現正常,但切換回System.Drawing.Common 就會徹底不認識 或者徹底變了字github

好比 :我是中文
畫出來後變成了web

 

 

 這徹底不是這個了,閱讀System.Drawing.Common的源碼也並無發現其中的坑在哪裏 ,跟ZKWeb.System.Drawing 也對比了下,centos

找到關鍵性代碼進行對比  System.Drawing.Common 中的源碼api

https://github.com/dotnet/corefx/blob/master/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs函數

 [DllImport(LibraryName, ExactSpelling = true, CharSet = CharSet.Unicode)]
 internal static extern int GdipDrawString(HandleRef graphics, string textString, int length, HandleRef font, ref RectangleF layoutRect, HandleRef stringFormat, HandleRef brush);

以及ZKWeb.System.Drawing中的源碼字體

 

https://github.com/zkweb-framework/ZKWeb.System.Drawing/blob/master/src/ZKWeb.System.Drawing/System.Drawing/gdipFunctions.csthis

[DllImport(GdiPlus, CharSet=CharSet.Unicode)]
 static internal extern Status GdipDrawString (IntPtr graphics, string text, int len, IntPtr font, ref RectangleF rc, IntPtr format, IntPtr brush);

進行對比 並無法發現什麼區別,因而就把這個定義放到本身的程序中定義 手動調用 GdipDrawString 看看是否會有中文亂碼的問題,然而發現換System.Drawing.Common中的定義或者ZKWeb.System.Drawing中的定義均可以正常顯示 但切換回System.Drawing.Common 使用系統的代碼spa

Graphics.DrawString 中文就是不行,看了下DrawString 的代碼也很是簡單 ,就是調用了GdipDrawString  api 繪畫字符串的,其源碼以下code

 public void DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format)
        {
            if (brush == null)
                throw new ArgumentNullException(nameof(brush));
            if (string.IsNullOrEmpty(s))
                return;
            if (font == null)
                throw new ArgumentNullException(nameof(font));

            CheckErrorStatus(Gdip.GdipDrawString(
                new HandleRef(this, NativeGraphics),
                s,
                s.Length,
                new HandleRef(font, font.NativeFont),
                ref layoutRectangle,
                new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero),
                new HandleRef(brush, brush.NativeBrush)));
        }

也沒有發現什麼異常,最後使用反編譯查看nuget包中的 System.Drawing.Common.dll 文件,竟然發現System.Drawing.Common.dll 中的GdipDrawString 竟然少了CharSet 標記,斷定是致使問題的所在,

因而懷疑是我沒有更新到最新版本致使的,上nuget一看發現是最新的版本 4.6的版本

 

 

因而估計是微軟沒更新致使的,暫時解決方法就是使用ZKWeb.System.Drawing 代替或者本身把這個api本身定義並拋棄系統的Graphics.DrawString 函數 

相關文章
相關標籤/搜索