Which unit of measurement does the Paint.setTextSize(float) use?

marzipankaiser picture marzipankaiser · Jul 30, 2012 · Viewed 10.2k times · Source

I want to draw text with an specific height(in pixels) on a view using Canvas. Can you simply use Paint.setTextSize(float) with the number of pixels or is this using dp or sp?

Answer

Todd Davies picture Todd Davies · Jul 30, 2012

It uses pixels, but you can convert it to dp using this code:

double getDPFromPixels(double pixels) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    switch(metrics.densityDpi){
     case DisplayMetrics.DENSITY_LOW:
                pixels = pixels * 0.75;
                break;
     case DisplayMetrics.DENSITY_MEDIUM:
                 //pixels = pixels * 1;
                 break;
     case DisplayMetrics.DENSITY_HIGH:
                 pixels = pixels * 1.5;
                 break;
    }
    return pixels;
}