简体   繁体   English

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

[英]Drawing “drawables” to a canvas in dp units

I'm trying to figure out if there is a way to draw bitmaps to the canvas in dp units instead of pixels. 我试图弄清楚是否有一种方法可以用dp单位而不是像素来绘制到画布的位图。 For example: the following code scales the drawable to 100 * 100 px. 例如:以下代码将drawable缩放为100 * 100 px。 How can I instead change it do 100 * 100 dp? 我怎样才能改变它做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. 另外,我不确定屏幕点击的测量单位是多少,但它们与屏幕上的像素不匹配,这使得很难检测到何时选择了一个drawable(你有点猜测在哪里点击到选择一个drawable。我可以将点击坐标缩放到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绘制的像素。

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

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

Source (@Romain Guy) 来源(@Romain Guy)

You can't directly, but you can convert between px and dp. 你不能直接,但你可以在px和dp之间转换。 See the answer in this related StackOverflow post for details. 有关详细信息,请参阅此相关StackOverflow帖子中的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM