java 以 dp 为单位将“drawables”绘制到画布上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6391823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:43:02  来源:igfitidea点击:

Drawing "drawables" to a canvas in dp units

javaandroidpixeltouchscreen

提问by cody

I'm trying to figure out if there is a way to draw bitmaps to the canvas in dp units instead of pixels. For example: the following code scales the drawable to 100 * 100 px. How can I instead change it do 100 * 100 dp?

我想弄清楚是否有办法以 dp 单位而不是像素将位图绘制到画布上。例如:以下代码将 drawable 缩放到 100 * 100 px。我怎样才能改变它做 100 * 100 dp?

int lengthPos = 10;
int heightPos = 10
mImage.setBounds(lengthPos, heightPos, (lengthPos + 100), (heightPos + 100));
mImage.draw(c);

Additionally, I'm not sure what the units of measurement for screen clicks are, but they don't match the pixels on the screen, making it hard to detect when a drawable has been selected (you kinda have to guess where to click to select a drawable. Can I also scale click coordinates to dp? doesn't seem like it would be too hard, especially since screen click coords are stored in a local variable for processing in my application.

此外,我不确定屏幕点击的测量单位是什么,但它们与屏幕上的像素不匹配,因此很难检测到何时选择了可绘制对象(您必须猜测点击的位置)选择一个可绘制对象。我也可以将点击坐标缩放到 dp 吗?似乎不会太难,特别是因为屏幕点击坐标存储在局部变量中以便在我的应用程序中进行处理。

In other words, I need to match the scaling so that clicking coordinates 250, 250 selects the pixels drawn at 250, 250 on multiple screen densities.

换句话说,我需要匹配缩放,以便单击坐标 250, 250 选择在多个屏幕密度上以 250, 250 绘制的像素。

回答by Aleadam

The ratio dp/dx is equal to your device dpi/160, so you can calculate dips easily this way.

比率 dp/dx 等于您的设备 dpi/160,因此您可以通过这种方式轻松计算倾角。

Use

利用

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
float density = dm.density

See the reference for more details: http://developer.android.com/reference/android/util/DisplayMetrics.html

有关更多详细信息,请参阅参考:http: //developer.android.com/reference/android/util/DisplayMetrics.html

回答by pomber

float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;

Source (@Romain Guy)

来源(@Romain Guy)

回答by kabuko

You can't directly, but you can convert between px and dp. See the answer in this related StackOverflow postfor details.

你不能直接,但你可以在 px 和 dp 之间转换。有关详细信息,请参阅此相关 StackOverflow 帖子中的答案。