Android 自定义View中drawText获取text宽度的三种方式
2016-06-29 17:20
661 查看
String str = "Hello"; canvas.drawText( str , x , y , paint); //1. 粗略计算文字宽度 Log.d(TAG, "measureText=" + paint.measureText(str)); //2. 计算文字所在矩形,可以得到宽高 Rect rect = new Rect(); paint.getTextBounds(str, 0, str.length(), rect); int w = rect.width(); int h = rect.height(); Log.d(TAG, "w=" +w+" h="+h); //3. 精确计算文字宽度 int textWidth = getTextWidth(paint, str); Log.d(TAG, "textWidth=" + textWidth); public static int getTextWidth(Paint paint, String str) { int iRet = 0; if (str != null && str.length() > 0) { int len = str.length(); float[] widths = new float[len]; paint.getTextWidths(str, widths); for (int j = 0; j < len; j++) { iRet += (int) Math.ceil(widths[j]); } } return iRet; }
转载自:http://blog.csdn.net/qin9r3y/article/details/8607014
相关文章推荐
- android应用内部实现生成桌面快捷方式与进度条控制音量大小
- Android中的“再按一次返回键退出程序”实现
- android源码解析之(一)-->android项目构建过程
- android--之笔记(一)
- Android项目研发之多分辨率适配
- 深入理解Android消息处理系统——Looper、Handler、Thread
- Android生命周期
- android控制系统回退按钮再按一次退出程序
- Android中的FlexboxLayout
- Activity的启动模式
- 通过js调用android原生方法
- Android开发环境搭建
- Android RecyclerView设置item间距
- Android取消EditText自动默认获取焦点行为
- Android 热补丁动态修复框架小结
- 安卓报错
- Android软键盘弹出,返回键Activity不结束
- Android跨进程通信之ContentProvider
- Android开发中RecyclerView组件使用的一些进阶技讲解
- Android 应用Crash Log在Logcat中消失的问题 threadid=1: thread exiting with uncaught exception