Android Text Size for Phone & Tablet in a Custom Renderer

Oregon39 156 Reputation points
2021-04-12T22:05:07.437+00:00

I'm drawing text on a custom map marker in a custom renderer (Android). The text shows up fine on a phone but in a tablet the text is way too large.
What is the best way to make the text adapt to both a phone and a tablet? In native android, one would use scalable pixels. How should this be approached in Xamarin Forms? Below is the relevant code:

public static BitmapDrawable WriteOnDrawable(Context context, int drawableId, String text, Color color)
{
Bitmap bitmap = BitmapFactory.DecodeResource(context.Resources, drawableId)
.Copy(Bitmap.Config.Argb8888, true);

     Paint paint = new Paint();
     paint.SetStyle(Paint.Style.Fill);
     paint.Color = color;
     paint.TextSize = 50;
     paint.TextAlign = Paint.Align.Center;
     paint.AntiAlias = true;
     Canvas canvas = new Canvas(bitmap);

     canvas.DrawText(text, bitmap.Width / 2 //x position
     , bitmap.Height / 2 // y position
     , paint);
     return new BitmapDrawable(context.Resources, bitmap);
     }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,293 questions
0 comments No comments
{count} votes

Accepted answer
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-04-13T05:42:03.567+00:00

    Hello,

    Welcome to Microsoft Q&A!

    We could use Device.Idiom to detect if it's on phone or Tablet .

    XAML

       <Setter Property="FontSize">  
               <Setter.Value>  
                    <OnIdiom x:TypeArguments="x:Double" Phone="15" Tablet="24"/>  
                </Setter.Value>  
         </Setter>  
    

    Code behind

       var font = (Device.Idiom == TargetIdiom.Phone) ? 15 : 24;  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    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