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?
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.
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.
The ratio dp/dx is equal to your device dpi/160, so you can calculate dips easily this way.
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
float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;
Source (@Romain Guy)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With