Question:
I want to draw text with an specific height(in pixels) on a view using
Answer:
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:
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;
}
These methods include
DisplayMetrics
that can be added into future Android SDK.
Pixels to dip:
public static float getDipFromPixels(float px) {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PX,
px,
Resources.getSystem().getDisplayMetrics()
);
}
Dip to pixels:
public static float getPixelsFromDip(float dip) {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip,
Resources.getSystem().getDisplayMetrics()
);
}