Is there a way to apply fonts to Android using .NET MAUI Canvas.Font?

재훈 장 20 Reputation points
2023-04-20T01:27:43.6133333+00:00

I created a character using graphic view during the user interface. So I used Canvas.Font, and the installed font was applied well in Windows.
But on Android, the font is not applied.
Is there a way to set up a font on Android in canvas without using Label's FontFamily? I'm not going to use Skisharp.

 public void Draw(ICanvas canvas, RectF dirtyRect)
        {

            canvas.FontColor = GetColor(TextColor);     //Font Color
            canvas.FontSize = GetFontSize(canvas);      //Font Size 
           
            canvas.Font = new Font(FontFaceType,SelectFontWeight.FontWeight(FontWeights));


            //배경색 사용을 하면은?
            if (IsBackColor)
            {
                SolidPaint solidPaint = new SolidPaint(GetColor(BackColor));
                RectF solidRectangle = new RectF(0, 0, Width, Height);
                canvas.SetFillPaint(solidPaint, solidRectangle);
                canvas.FillRoundedRectangle(solidRectangle, 0);
            }

            //Draw Text!

            TextString = TextString.Replace("|", "\r\n");

            canvas.DrawString(TextString, Xpoint, Ypoint, Width, Height, HorizontalAlignment, VerticalAlignment);

         

        }
Developer technologies .NET .NET MAUI
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-04-20T06:23:33.0966667+00:00

    Hello,

    After my testing, you could refer to the following steps to get your font file to work on Android.

    Step 1: Add and register a font file called MyFont by this document: Fonts - Register fonts.

    fonts.AddFont("MyFont.ttf", "MyFont");
    

    Step 2: In the Draw method, when creating a font object for the Android platform, you need to include the suffix to take effect:

    #if WINDOWS 
                canvas.Font = new Font(FontFaceType,SelectFontWeight.FontWeight(FontWeights));
    #elif ANDROID
                canvas.Font = new Font("MyFont.ttf", 18);
    #endif
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.