8

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.

alain.janinm
  • 19,951
  • 10
  • 65
  • 112
cody
  • 735
  • 3
  • 11
  • 19

3 Answers3

8

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

Aleadam
  • 40,203
  • 9
  • 86
  • 108
7
float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;

Source (@Romain Guy)

Community
  • 1
  • 1
pomber
  • 23,132
  • 10
  • 81
  • 94
1

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

Community
  • 1
  • 1
kabuko
  • 36,028
  • 10
  • 80
  • 93