我扩展了 View 来构建自定义小部件。我想用独立的像素单位定义小部件的高度。
我认为可以通过将像素密度乘以所需的高度来完成,但我不知道该怎么做。
到目前为止我所拥有的(最小化):
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);
}
}
所以我想改变线路
this.setMeasuredDimension(widthMeasureSpec, 50);
and
rect.set(0, 0, canvasWidth, 50);
与像素无关的东西。
Thanks
将像素值乘以getResources().getDisplayMetrics().density
使像素与密度无关。如果您绘制文本,您可能需要使用scaledDensity。
我相信 mdpi 上的密度 = 1,hdpi 上的密度 = 1.5,ldpi 上的密度 = 0.75。
为了完成答案,一些源代码:
处理视图或图像时使用以下内容
int px = getResources().getDisplayMetrics().density * dp;
或者,在处理文本时:
int px = getResources().getDisplayMetrics().scaledDensity * sp;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)