Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a pixel independent height in an onDraw() method

I have extended View to build a custom widget. I would like to define the height of the widget with an independ pixel unit. I think it could be done by multiplying the pixel density by the desired height , but i don't know how to do that.

What i have so far (minimized) :

public class Timeline extends View 
{

    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        int canvasWidth = canvas.getWidth();
        this.widgetWith = canvasWidth;


        this.setBackgroundGradientNoVideo();
        RectF rect = new RectF();
        rect.set(0, 0, canvasWidth, 50);
        //Dessin d'un rectangle de fond
        canvas.drawRoundRect(rect, 10, 10, this.paint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        //super.onMeasure(widthMeasureSpec, 50);
        this.setMeasuredDimension(widthMeasureSpec, 50);
        this.widgetWith = MeasureSpec.getSize(widthMeasureSpec);
    }
}

So i would like to change the lines

this.setMeasuredDimension(widthMeasureSpec, 50);

and

rect.set(0, 0, canvasWidth, 50);

To something pixel independent.

Thanks

like image 684
grunk Avatar asked Aug 11 '11 15:08

grunk


2 Answers

multiply your pixel values by getResources().getDisplayMetrics().density to make pixels density-independent. If you draw text, you might want to use scaledDensity instead.

density = 1 on mdpi, 1.5 on hdpi, and 0.75 on ldpi i believe.

To complete the answer, some source code:

Either use the following when dealing with views or images

int px = getResources().getDisplayMetrics().density * dp;  

Or, when dealing with text:

int px = getResources().getDisplayMetrics().scaledDensity * sp;
like image 120
MrJre Avatar answered Sep 23 '22 17:09

MrJre


To get px values from dp values, calculate

int px = getResources().getDisplayMetrics().density * dp;

I recommend to place a static method somewhere which takes the dp value as parameter in order to do this with less code. E.g. I created a class "ResolutionHelper" which is initialized with the correct density value on app start and which has a static method "dipToPx(int dip) that can then used from anywhere.

like image 37
didi_X8 Avatar answered Sep 23 '22 17:09

didi_X8