I can't seem to get text positioned in the same places on screens of different resolution. The problem is the text is floating, it's not part of any layout type of control.
I try to position the text in relative units compared the screen size. For example, I put it at 50% on the X and 67.89% on the Y axis. Despite that, the text appears in a different location on different resolution screens.
So I'm stuck approximating the location for certain resolutions and this gets messy really fast.
How can I pin point a location on a canvas that is the same spot despite the DPI / screen size?
Use DisplayMetrics to calculate the distance. For example if you always want the text to be 1.5 inches from the left and top.
This will work with any View or Bitmap you drawing on.
draw(Canvas canvas){
Matrix identity = new Matrix; // Used to have canvas draw on
Matrix savedMatrix = new Matrix();
canvas.getMatrix(savedMatrix);
canvas.setMatrix(identity);
float y = displayMetrics.ydpi * 1.5;
float x = displayMetrics.xdpi * 1.5;
canvas.drawText(text, x, y + paint.getTextSize(), paint);
canvas.setMatrix(savedMatrix);
}
Information about the overall display density (as well as other metrics) is available in the DisplayMetrics class. You can retrieve it like this:
void getMetrics(Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
}
http://developer.android.com/reference/android/util/DisplayMetrics.html
You can scale all coordinates to account for screen density like this:
void scaleForDensity(DisplayMetrics metrics, Point point) {
point.x = (int)(point.x*metrics.density + .5f);
point.y = (int)(point.y*metrics.density + .5f);
}