当前位置: 代码迷 >> Android >> Android使用StaticLayout实现文本作图自动换行
  详细解决方案

Android使用StaticLayout实现文本作图自动换行

热度:62   发布时间:2016-04-28 02:49:29.0
Android使用StaticLayout实现文本绘制自动换行

使用的场景主要是绘制文本的时候指定绘制区域的宽度,文本需要根据宽度自动换行。



使用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);	}}

?

?完。

  相关解决方案