Android Canvas - 在所有屏幕分辨率的位置文本与drawText在同一位置 [英] Android Canvas - Position text with drawText in the same location on all screen resolutions

查看:568
本文介绍了Android Canvas - 在所有屏幕分辨率的位置文本与drawText在同一位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在不同分辨率的屏幕上的相同位置找到文本。问题是文本是浮动的,它不是任何布局类型的控件的一部分。



我尝试以相对单位定位文本,与屏幕大小相比。例如,我把它的X轴上的50%和Y轴上的67.89%。尽管如此,文本显示在不同的分辨率屏幕上的不同位置。



所以我卡住了近似于某些分辨率的位置,这变得非常快。 p>

尽管DPI /屏幕尺寸相同,但如何在画布上固定某个位置?

解决方案

使用 DisplayMetrics 计算距离。例如,如果你总是希望文本从左边和顶部1.5英寸。



这将适用于您绘制的任何视图或位图。

  draw(Canvas canvas){
Matrix identity = new Matrix; //用于在
上绘制画布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);
}


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);
}

这篇关于Android Canvas - 在所有屏幕分辨率的位置文本与drawText在同一位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆