安卓获取TextView中字符串占屏幕宽度的方法

来源:互联网 发布:风险指数矩阵举例 编辑:程序博客网 时间:2024/03/29 00:57

public static int getLineLength(String str, float textSize) {
  Paint pFont = new Paint();
  pFont.setTextSize(textSize);
  return (int) pFont.measureText(str);
 }

 

str为TextView获取的字符串,textSize为字符串的字符的字号,单位是像素(px),

返回值的单位也是px.

可以使用

public static int dip2px(Context context, float dpValue) { 
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  

}

public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
 这两个方法转换dp 和px 单位, 

 

0 0
原创粉丝点击