How to determine pixel-independent height in the onDraw () method

I have an advanced view for creating a custom widget. I would like to determine the height of the widget with an independent pixel block. I think this can be done by multiplying the pixel density by the desired height, but I do not know how to do it.

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); 

Something pixel is not dependent.

thanks

+6
source share
2 answers

multiply the pixel values ​​by getResources().getDisplayMetrics().density to make the pixels independent of density. If you draw text, you can use scaledDensity instead.

density = 1 at mdpi, 1.5 at hdpi and 0.75 at ldpi, I suppose.

To execute the answer, some source code:

When working with views or images, use the following:

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

Or when it comes to text:

 int px = getResources().getDisplayMetrics().scaledDensity * sp; 
+16
source

To get px values ​​from dp values, calculate

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

I recommend putting a static method somewhere that takes a dp value as a parameter to do this with less code. For instance. I created the “ResolutionHelper” class, which is initialized with the correct density value at the beginning of the application and which has the static method “dipToPx (int dip), which can then be used from anywhere.

+13
source

Source: https://habr.com/ru/post/894848/