question

Oregon39-5606 avatar image
0 Votes"
Oregon39-5606 asked Oregon39-5606 commented

Android Text Size for Phone & Tablet in a Custom Renderer

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



dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ColeXia-MSFT avatar image
0 Votes"
ColeXia-MSFT answered Oregon39-5606 commented

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.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@ColeXia-MSFT Thanks so much for your response. That is indeed the solution to the issue. I put in the specific numeric values for my particular case and it works great. Thanks!

0 Votes 0 ·