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