Android文本的测量和绘制
来源:互联网 发布:爬虫怎么找兼职 知乎 编辑:程序博客网 时间:2024/06/13 10:50
翻译与 Chris Banes的博客 原文地址
如果你想手动在Android Canvas上画些什么东西,你最好从绘制文本开始。
文本绘制之前,你需要知道测量文本的绘制位置,计算文本X/Y轴的位置。
最近我在一款APP中,需要在横向和纵向的画布上绘制一些以文本为中心的文字。于是我用了下面这些代码:
Paint mTextPaint = new Paint(); mTextPaint.setTextAlign(Paint.Align.CENTER); // Center the text// Later when you draw...canvas.drawText(mText, // Text to display mBounds.centerX(), // Center X of canvas bounds mBounds.centerY(), // Center Y of canvas bounds mTextPaint);
我没想到代码的运行后竟然是下面的这个样子:
测量文本
接下来,我尝试定位文本,计算了文本的高宽度,并且修改了绘制文本X轴Y轴的位置:
int mTextWidth, mTextHeight; // Our calculated text bounds Paint mTextPaint = new Paint();// Now lets calculate the size of the textRect textBounds = new Rect(); mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds); mTextWidth = textBounds.width(); mTextHeight = textBounds.height();// Later when you draw...canvas.drawText(mText, // Text to display mBounds.centerX() - (mTextWidth / 2f), mBounds.centerY() + (mTextHeight / 2f), mTextPaint);这一次我们做的已经相当接近了,但是你可以看到文本还是没有居中。
为了确定我没看到的原因,我用Paint.getTextBounds()计算一个矩形,并画在了文本的后面。
正如你看到的,文本的高宽绘制在了计算范围之外。
另一中测量文本的方法
在这个基础点上,我看到Paint另一种计算文本宽度的方法:Paint.measureText()
这个方法只能计算宽度而不能计算高度,因此我尝试结合两种方法:
int mTextWidth, mTextHeight; // Our calculated text bounds Paint mTextPaint = new Paint();// Now lets calculate the size of the textRect textBounds = new Rect(); mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds); mTextWidth = mTextPaint.measureText(mText); // Use measureText to calculate width mTextHeight = textBounds.height(); // Use height from getTextBounds()// Later when you draw...canvas.drawText(mText, // Text to display mBounds.centerX() - (mTextWidth / 2f), mBounds.centerY() + (mTextHeight / 2f), mTextPaint);这几下就做出了完美居中的文本。悠嘻!
0 0
- Android文本的测量和绘制
- Android文本的测量和绘制
- Android文本的测量和绘制
- Android控件架构与view,viewgroup的测量和绘制
- Android控件架构及View、ViewGroup的测量和绘制
- Android群英传---View、ViewGroup的测量和绘制
- Android群英传读书笔记---View测量和绘制
- 【Android自定义View】测量和绘制浅析
- ViewGroup的测量与绘制(Android群英传)
- View和ViewGroup的测量与绘制
- Android文本测量
- ViewGroup的测量、绘制
- View的测量 绘制
- android 之view的测量和绘制(群英传读书笔记1)
- Android应用程序窗口Activity的测量Measure布局Layout和绘制Draw过程分析
- Android学习笔记(一) View、ViewGroup的测量绘制
- Android文字测量与绘制的两个注意点
- View和ViewGroup的测量与绘制过程总结
- MPTCP 源码分析(七) 拥塞控制
- BNU Training 2016.07.25 总结
- C语言系列(二)有符号数和无符号数详解
- CodeForces 501C Misha and Forest (STL queue)(拓扑排序)
- BestCoder Round #86 HDU 5804(暴力),HDU 5805(前缀和后缀差值最大),HDU 5806(尺取法),HDU 5807(简单DAG 分步式DP )
- Android文本的测量和绘制
- UVA 10305 Ordering Tasks(拓扑排序入门)【刘汝佳算法入门经典例6-15】
- Head First 装饰者模式
- 多线程实现的三个方法
- leetcode No86. Partition List
- 安卓端的音乐播放
- hdu2141
- HDU-5806-NanoApe Loves Sequence Ⅱ-DP+队列维护
- 深度学习概述:从感知机到深度网络 (英文版)