Which unit of measurement does the Paint.setTextSize(float) use?

萝らか妹 提交于 2019-12-22 01:51:59

问题


I want to draw text with an specific height(in pixels) on a view using Canvas. Can you simply use Paint.setTextSize(float) with the number of pixels or is this using dp or sp?


回答1:


It uses pixels, but you can convert it to dp using this code:

double getDPFromPixels(double pixels) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    switch(metrics.densityDpi){
     case DisplayMetrics.DENSITY_LOW:
                pixels = pixels * 0.75;
                break;
     case DisplayMetrics.DENSITY_MEDIUM:
                 //pixels = pixels * 1;
                 break;
     case DisplayMetrics.DENSITY_HIGH:
                 pixels = pixels * 1.5;
                 break;
    }
    return pixels;
}



回答2:


The easiest way to get a px value for such methods is to simply define the appropriate dp or sp value in the dimens.xml file and retrieve it like this:

int sizeInPx = context.getResources().getDimensionPixelSize(R.dimen.sizeInSp);

You actually have 3 methods available to use depending on your needs:

  • getDimension() Returns a float in pixels.

  • getDimensionPixelSize() Returns an int in pixels. This is the same as getDimension(), except the returned value is ROUNDED to the nearest integer value and it ensures that a non-zero input value results in a non zero output value (eg 0.1 is returned as 1, not 0).

  • getDimensionPixelOffset() Returns an int in pixels. This is the same as getDimension(), except the returned value is TRUNCATED (ie. rounded down). The result may be zero.




回答3:


These methods include DisplayMetrics that can be added into future Android SDK.

Pixels to dip:

public static float getDipFromPixels(float px) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_PX,
                px,
                Resources.getSystem().getDisplayMetrics()
        );
}

Dip to pixels:

public static float getPixelsFromDip(float dip) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 
                dip,
                Resources.getSystem().getDisplayMetrics()
        );
}


来源:https://stackoverflow.com/questions/11720093/which-unit-of-measurement-does-the-paint-settextsizefloat-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!