Saturday, January 26, 2013

Draw Text on Canvas with Font Size Independent of Screen Resolution - Android

I will show how to draw text with a font size independent of screen resolution on to a canvas.
First we need to create an XML and place it in res/values. Call the file myFontSize. The following is the content of the file


    20sp

Here is a sample use and how to implement.
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class MainActivity extends Activity
{
 Paint paint;

 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  paint = new Paint();
  View test = new TestView(this);

  setContentView(test);
 }

 public class TestView extends View
 {

  public TestView(Context context)
  {
   super(context);
   setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  }

  @Override
  protected void onDraw(Canvas canvas)
  {
   int size = getResources().getDimensionPixelSize(R.dimen.myFontSize);
   paint.setColor(Color.BLACK);
   paint.setTextSize(size);
   canvas.drawText("HELLOOOOOOOOOOOOOO!", 0, size, paint);
   super.onDraw(canvas);
  }
 }
}

The magic happens on the call to getResources().getDimensionPixelSize(..). This function grabs your set font size (in this case 20sp) and returns it as an appropriate size to give to your paint. Paint is the attributes which will tell the canvas what to do to the provided text.

You should see the following on different resolutions



1 comment:

  1. This tutorial is incredibly helpful for anyone looking to draw text on a canvas in an Android app. The step-by-step instructions are easy to follow, and Paint and Rect objects are explained thoroughly. Additionally, the tip about using a college coursework helper to review your code and offer suggestions is a great idea for those looking to take their skills to the next level. Overall, this tutorial provides a solid foundation for anyone looking to add custom text to their Android app.

    ReplyDelete