开发者

Android Canvas - Position text with drawText in the same location on all screen resolutions

开发者 https://www.devze.com 2023-03-31 11:37 出处:网络
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 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号