如何在onDraw()方法中定义像素独立的高度 [英] How to define a pixel independent height in an onDraw() method

查看:137
本文介绍了如何在onDraw()方法中定义像素独立的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经扩展了View以构建自定义窗口小部件。我想用独立像素单位定义小部件的高度。
我认为可以通过将像素密度乘以所需的高度来完成,但是我不知道该怎么做。

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

所以我想换行

this.setMeasuredDimension(widthMeasureSpec, 50);

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

要与像素无关。

谢谢

推荐答案

将像素值乘以 getResources()。getDisplayMetrics()。density 使像素密度无关。如果您绘制文本,则可能要改用scaledDensity。

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

我相信密度在mdpi上为1,在hdpi为1.5,在ldpi为0.75。

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

要完成答案,请提供一些源代码:

在处理视图时,请使用以下内容:图片

Either use the following when dealing with views or images

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

或者,在处理文本时:

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

这篇关于如何在onDraw()方法中定义像素独立的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆