使用的场景主要是绘制文本的时候指定绘制区域的宽度,文本需要根据宽度自动换行。
使用TextPaint和StaticLayout就可以实现这个功能,并可以获得绘制后的文本区域的高度:
- package com.hu.text;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Paint.Style;
- import android.text.Layout.Alignment;
- import android.text.StaticLayout;
- import android.text.TextPaint;
- import android.view.MotionEvent;
- import android.view.View;
- import com.example.texttest.R;
- public class MyView extends View {
- TextPaint textPaint = null;
- StaticLayout staticLayout = null;
- Paint paint = null;
- int width = 50;
- int height = 0;
- String txt = null;
- boolean running = false;
- public MyView(Context context) {
- super(context);
- textPaint = new TextPaint();
- textPaint.setAntiAlias(true);
- textPaint.setTextSize(12);
- txt = getResources().getString(R.string.my_text);
- staticLayout = new StaticLayout(txt, textPaint, width, Alignment.ALIGN_NORMAL, 1, 0, false);
- height = staticLayout.getHeight();
- paint = new Paint();
- paint.setStyle(Style.STROKE);
- paint.setColor(Color.RED);
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- running = !running;
- if(running){
- new Thread(){
- public void run() {
- while(running){
- width ++;
- staticLayout = new StaticLayout(txt, textPaint, width, Alignment.ALIGN_NORMAL, 1, 0, false);
- height = staticLayout.getHeight();
- postInvalidate();
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(width >= 300){
- width = 50;
- }
- }
- };
- }.start();
- }
- break;
- default:
- break;
- }
- return super.onTouchEvent(event);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- // TODO Auto-generated method stub
- canvas.translate(20, 20);
- staticLayout.draw(canvas);
- canvas.drawRect(0, 0, width, height, paint);
- super.onDraw(canvas);
- }
- }
完。