Masahiko Miyasaka
Masahiko Miyasaka

Reputation: 191

How to draw Japanese text with SkiaSharp on Xamarin

Now I'm using SkiaSharp on Xamarin Android.

I wanna draw Japanese text with SKCanvas.DrawText ,but japanese characters were garbled.

I saw this similar question,so I tried to convert text to UTF-8, but result is same.

I tried like below.

var s = "abcあいう123壱弐参";
var buf = System.Text.Encoding.UTF8.GetBytes(s);
var utf8s = Encoding.UTF8.GetString(buf);
skcanvas.DrawText(utf8s, 50, 50, paint);

another one.

var s = "abcあいう123壱弐参";
var dest = Encoding.UTF8;
var src = Encoding.Default;
var buf = src.GetBytes(s);
var buf2 = Encoding.Convert(src,dest, buf);
var utf8s = dest.GetString(buf2);
skcanvas.DrawText(utf8s, 50, 50, paint);

Both result are same. "abc" and "123" is drawn well,but Japanese character are garbled.

Any idea?

Upvotes: 3

Views: 2456

Answers (2)

Ria Lightman
Ria Lightman

Reputation: 21

You can use "matchCharacter()", input param might be just a Japanese character, like "あ"

var japanese = fontManager.MatchCharacter("Courier New", '年')
paint.Typeface = japanese;
canvas.DrawText("abcあいう123", x, 300, paint);

Refer link: https://github.com/mono/SkiaSharp/blob/master/samples/SkiaSharpSample.Shared/Samples/UnicodeTextSample.cs

Upvotes: 2

SushiHangover
SushiHangover

Reputation: 74194

Assuming you are loading a custom font, like Uzumasa Honmaru Gothic, you can add it to each of your native platform project and then use it via that native project or a Xamarin.Forms-based one:

Android:

string fontName = "UzumasaFontMini.otf";
string fontPath = Path.Combine (CacheDir.AbsolutePath, fontName);
using (var asset = Assets.Open (fontName))
using (var dest = File.Open (fontPath, FileMode.Create)) {
    asset.CopyTo (dest);
}
string customFontPath = fontPath;

iOS:

string fontName = "UzumasaFontMini.otf";
string customFontPath = NSBundle.MainBundle.PathForResource (Path.GetFileNameWithoutExtension (fontName), Path.GetExtension (fontName));

DrawText:

string text = "abcあいう123";
using (var paint = new SKPaint ()) {
    canvas.Clear (SKColors.Black);
    paint.IsAntialias = true;

    using (var tf = SKTypeface.FromFile (customFontPath)) {
        paint.Color = SKColors.White;
        paint.TextSize = 20;
        paint.Typeface = tf;

        canvas.DrawText (text, 50, 50, paint);
    }
}

Android:

enter image description here

iOS:

enter image description here

Upvotes: 5

Related Questions