如何绘制在一个盒子里的文本在画布上用DynamicLayout和Ellipsize [英] How to draw a text inside a box on canvas with DynamicLayout and Ellipsize
问题描述
我要画在画布上的文本中的特殊框。我已经使用DynamicLayout自动计算和断行,以适应框宽度内。现在我需要自动ellipsize文本以适应框的高度。
我怎样才能做到这一点?它不一定需要是由高度(像素),也可能是由线的最大数量。
例如:
这是为了适应箱内示例文本
实际结果:
------------
|这是一个|
|文|
|装进|
------------
包装盒
预期成果:
------------
|这是一个|
|文|
|适合... |
------------
我创建这样的DynamicLayout:
的TextLayout =新DynamicLayout(MTEXT,mTextPaint,100,Alignment.ALIGN_NORMAL,1.0F,0.0,FALSE);
然后,我画它是这样的:
canvas.save();
canvas.translate(500,500 - textLayout.getHeight()/ 2);
textLayout.draw(画布);
canvas.restore();
据我所知线( mMaxLines
)适合框里面的号码,我延长了DynamicLayout我overrided的几种方法:
@覆盖
公众诠释getLineCount(){
如果(super.getLineCount() - 1> mMaxLines){
返回mMaxLines;
}
返回super.getLineCount() - 1;
}
@覆盖
公众诠释getEllipsisCount(INT线){
如果(线== mMaxLines - 1安培;&安培; super.getLineCount() - 2 - ;线){
返回1;
}
返回0;
}
@覆盖
公众诠释getEllipsisStart(INT线){
如果(线== mMaxLines - 1安培;&安培; super.getLineCount() - 2 - ;线){
返回getLineEnd(线) - getLineStart(线) - 1;
}
返回0;
}
然后,我有以下结果:
------------
|这是一个|
|文|
|适合... |
------------
I need to draw a text on canvas inside a specific box. I'm already using DynamicLayout to automatically calculate and break lines to fit inside the box width. Now I need to ellipsize the text automatically to fit the box height.
How can I achieve this? It doesn't necessarily need to be by the height (pixels), it could be by the max number of lines.
Example:
"This is a sample text to fit inside the box"
Actual Result:
------------
|This is a |
|text to |
|fit inside|
------------
the box
Expected Result:
------------
|This is a |
|text to |
|fit in... |
------------
I create the DynamicLayout like this:
textLayout = new DynamicLayout(mText, mTextPaint, 100, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
And then I draw it like this:
canvas.save();
canvas.translate(500, 500 - textLayout.getHeight() / 2);
textLayout.draw(canvas);
canvas.restore();
As I know the number of lines (mMaxLines
) that fit inside the box, I extended the DynamicLayout and I overrided a few methods:
@Override
public int getLineCount() {
if (super.getLineCount() - 1 > mMaxLines) {
return mMaxLines;
}
return super.getLineCount() - 1;
}
@Override
public int getEllipsisCount(int line) {
if (line == mMaxLines - 1 && super.getLineCount() - 2 > line) {
return 1;
}
return 0;
}
@Override
public int getEllipsisStart(int line) {
if (line == mMaxLines - 1 && super.getLineCount() - 2 > line) {
return getLineEnd(line) - getLineStart(line) - 1;
}
return 0;
}
Then I have the following result:
------------
|This is a |
|text to |
|fit in... |
------------
这篇关于如何绘制在一个盒子里的文本在画布上用DynamicLayout和Ellipsize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!