-
Notifications
You must be signed in to change notification settings - Fork 21
解决Canvas的drawText绘制文本是不会自动换行的 staticlayout
Mr.wu edited this page Mar 27, 2017
·
1 revision
使用Canvas的drawText绘制文本是不会自动换行的,即使一个很长很长的字符串,drawText也只显示一行,超出部分被隐藏在屏幕之外。可以逐个计算每个字符的宽度,通过一定的算法将字符串分割成多个部分,然后分别调用drawText一部分一部分的显示, 但是这种显示效率会很低。
StaticLayout是android中处理文字换行的一个工具类,StaticLayout已经实现了文本绘制换行处理,下面是如何使用StaticLayout的例子:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View {
Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs){
super(context, attrs);
}
public void onDraw(Canvas canvas){
super.onDraw(canvas);
TextPaint tp = new TextPaint();
tp.setColor(Color.BLUE);
tp.setStyle(Style.FILL);
tp.setTextSize(50);
String message = "paint,draw paint指用颜色画,如油画颜料、水彩或者水墨画,而draw 通常指用铅笔、钢笔或者粉笔画,后者一般并不涂上颜料。两动词的相应名词分别为p";
StaticLayout myStaticLayout = new StaticLayout(message, tp, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
myStaticLayout.draw(canvas);
canvas.restore();
}
}
}