Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 472
cody Avatar asked Jun 17 '11 21:06

cody


2 Answers

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

like image 113
Aleadam Avatar answered Oct 01 '22 22:10

Aleadam


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

Source (@Romain Guy)

like image 21
pomber Avatar answered Oct 01 '22 23:10

pomber