Android使用StaticLayout实现文本绘制自动换行
来源:互联网 发布:育知同创教育位置 编辑:程序博客网 时间:2024/06/02 23:47
使用的场景主要是绘制文本的时候指定绘制区域的宽度,文本需要根据宽度自动换行。
使用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);
- }
- }
完。
0 0
- Android使用StaticLayout实现文本绘制自动换行
- android staticlayout使用讲解,可实现文本绘制换行处理
- android TextView不会自动换行怎么办,教你使用staticlayout解决换行
- android staticlayout使用讲解
- android staticlayout使用详解
- android staticlayout使用讲解
- 自动换行StaticLayout的简单介绍
- html5-canvas的绘制文本自动换行
- Android绘制字符串自动换行
- 使用verctor文本自动换行
- j2me在Canvas上绘制大量文本自动换行的实现
- android bitmap绘制文字自动换行
- android bitmap绘制文字自动换行
- JavaMe 编程连载(4) - 绘制可自动换行文本
- Canvas的drawText绘制文本不自动换行的解决
- 文字换行StaticLayout
- 实现文本、数字、英文字母自动换行!
- Android自定义view-文本自动换行
- iOS中OC与JS的简单交互
- 将字符串按字符个数切割成数组
- 人工智能的JAVA实现
- GRE满分作文分析
- Axure画Android原型
- Android使用StaticLayout实现文本绘制自动换行
- tcptrace
- 水题NYOJ1071【不可以!】
- 用cronolog为tomcat做日志分割之问题解决版
- Graham's Scan法求解凸包问题(C++)
- June。。。。。。
- C++ 10.3 关联容器map定义以及value_type、key_type、mapped_type
- 代理模式原理及实例讲解
- IOException while loading persisted sessions