Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dp to pixels and and use it to draw to canvas in android

Tags:

android

canvas

I'm trying to convert dp to pixels. I'm using this method:

//Converts device pixels to regular pixels to draw
private float dpToPixel(float dp) {
    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    float px = dp * (metrics.densityDpi/160f);
    return px;
}

Then I try to get the dp from a variable in my dimen.xml file, like this:

int buttonWidth = (int) dpToPixel(R.dimen.buttonHeight);

Then I create a scaled bitmap with the width of the buttonWidth variable. Then finally I draw it to the canvas. But when I try to run it, nothing is displayed. Can anyone help?

like image 747
Python and Android for life Avatar asked Aug 23 '15 02:08

Python and Android for life


1 Answers

I think there's either a typo in your question or you really don't load the value for the height - you are actually loading a number representing the id of the resource. It should have been:

int buttonWidth = (int) dpToPixel(getResorces().getDimension(R.dimen.buttonHeight));

But...you don't need to do the transformation yourself:

getResources().getDimensionPixelSize(R.dimen.buttonHeight);
like image 164
N.T. Avatar answered Sep 18 '22 12:09

N.T.