Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android text size on Canvas differ from text size in TextView

I have a SurfaceView and TextView on which I drawing a text

Paint p = new Paint();
p.p.setTextSize(14);
canvas.drawText(....
TextView  text =...
text.setTextSize(14);

On some devices both texts looks absolutely the same. But on an emulator and Samsung Galaxy III the text on canvas is twice smaller. Why? How to get same size on all devices?

The SurfaceView and TextView are on the screen in the same time. The TextView lay on several Layers and overlaid on Canvas of SurcafeView.

Best Regards

like image 558
Catherine Ivanova Avatar asked Apr 19 '13 11:04

Catherine Ivanova


1 Answers

You must make use of Device independent Pixels(dp/dip) in android to get same size on all devices. In case of Text there is scale-independent pixels(sp). check out more about these for better understanding.

To convert Pixel value into dp use the following code:

public static float convertPixelsToDp(float px,Context context){

  DisplayMetrics metrics = context.getResources().getDisplayMetrics();
  float dp = px / (metrics.densityDpi / 160f);
  return dp;

}

To convert dp value into pixel use the following code:

public static float convertDpToPixel(float dp,Context context){

  DisplayMetrics metrics = context.getResources().getDisplayMetrics();
  float px = dp * (metrics.densityDpi/160f);
  return px;

}

just call whichever method you want for your requirement.

like image 60
SKK Avatar answered Oct 20 '22 11:10

SKK