Android snippet: converting DIP / DP to pixels

Sometimes in android you have to deal with pixels, such as view.setPadding(int, int, int, int).  Obviously this is not ideal but no fear, there is a way to work around this.

Simply come up with the value you want in dip, say 10, and then convert into pixels like so:

float sizeInDip = 10f;
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sizeInDip, getResources().getDisplayMetrics());

Naturally you’ll need access to your resources (context.getResources() etc.).  Note that I’ve just cast this to an int here, you may want to round it up either.

 

One thought on “Android snippet: converting DIP / DP to pixels

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s