(1)canvas.draw(content,x,y,paint)方法中,
x:以x位置作为左边,向右绘制 |content
y:设置画笔的起始位置,是往上绘制的 __content ( __:可以理解成底线,content是内容的位置 )
(2)怎么获取某一段文字呢?
//用来获取 整一块的内容 可以看成是View的Content部分
//将text设置上去后,已经完成了分行
Layout layout=getLayout();
//获取某一段文字
//获取某一行文字的开始和结束位置的坐标
//在layout中已经是将文字换好行了,可以得到某一行的文字 (在整个文本中的位置坐标index,排版只是将这一行的文字间隔加大,内容是一样的,相当于“asdfg”显示成成“a s d f g”)
int lineStart=layout.getLineStart(i);
int lineEnd = layout.getLineEnd(i);
(3)怎么获取某一文字的宽度呢?
float width= StaticLayout.getDesiredWidth(rawText,lineStart,lineEnd,getPaint());
(3)textView的排版 (不过这种方法读取操作好像有点多)
public class View_myTest extends TextView {
public View_myTest(Context context) {
super(context);
}
public View_myTest(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 思路,将每一行剩余的空间均分到每个字符的间隔中
* (1)取到每一行的内容
* (2)取到每一行实际使用宽度
* (3)计算剩余 多出来的空间
* (4)逐个绘制字符并添加间隔
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
String rawText=getText().toString();
Paint paint=getPaint();
//绘制内容的起始Y轴
float cur_Y=paint.getTextSize();
//这里可以理解为绘制到canvas上的那些内容
//A base class that manages text layout in visual elements on the screen.
//For text that will be edited, use a DynamicLayout, which will be updated as the text changes. For text that will not change, use a StaticLayout.
Layout layout=getLayout();
//看一下一共多少行
int line_count=layout.getLineCount();
//第一行需要加两个空格
// canvas.drawText(" ",0,cur_Y,paint);
//当前字符在View中的位置的位置
float cur_x=getPaddingLeft();
//对每一行进行处理,最后一行不用管
for(int i=0;i<line_count-1;i++){
//获得当前行的内容
//当前行行首在raawText中的位置
int cur_line_start=layout.getLineStart(i);
//当前行行尾在rawTextView中的位置
int cur_line_end=layout.getLineEnd(i);
//当前行的内容
String cur_line_content=rawText.substring(cur_line_start,cur_line_end);
//得到当前字体占的宽度
float content_width= StaticLayout.getDesiredWidth(cur_line_content, getPaint());
//得到控件的宽度
float viewWidth=getMeasuredWidth();
//得到剩余空间
float rest_space=viewWidth-content_width-getPaddingRight()-getPaddingLeft();
//计算字体间应该增加的间隔
float between_space=(rest_space)/(cur_line_end-cur_line_start);
//一个字体的实际占据宽度
// float char_width=
//一个字实际占据的宽度
// float char_width=paint.measureText()
//逐字绘制
for(int j=0;j<cur_line_content.length();j++){
canvas.drawText(String.valueOf(cur_line_content.charAt(j)),cur_x,cur_Y,paint);
//有两种方法获取
float bw = StaticLayout.getDesiredWidth(String.valueOf(cur_line_content.charAt(j)), getPaint());
float bw1=paint.measureText(String.valueOf(cur_line_content.charAt(j)))
//增加了间隔
cur_x+=bw+between_space;
}
cur_x=getPaddingLeft();
cur_Y+=paint.getTextSize();
}
// String line=layout.ge
// canvas.drawText(content,40,paint.getTextSize(),paint);
// canvas.drawText(content,0,paint.getTextSize()*2,paint);
}
}