我正在使用Java2D TextLayout
类以及LineBreakMeasurer
和AttributedCharacterIterator
将一段文字绘制到一个框中。文字已被包裹。
分析显示代码非常慢。大部分时间都在方法TextLayout.draw(..)
中丢失。
有没有人建议提速?
// Get iterator for string
AttributedCharacterIterator iterator = attribText.getIterator();
// Create measurer
LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, context);
// loop over the lines
int i = 1;
while (measurer.getPosition() < iterator.getEndIndex()) {
// Get line
TextLayout textLayout = measurer.nextLayout(w);
// get measurements
float ascent = textLayout.getAscent();
float descent = textLayout.getDescent();
float leading = textLayout.getLeading();
float size = ascent + descent;
// Move down to baseline
if( i == 1 ) {
if( coverType == CoverType.SPINE ) {
y = (box.height-size)/2;
y -= (size+leading)*(lines-1)/2;
} else if( vAlign == Alignment.Center ) {
y += (h-size)/2-(size+leading)*(lines-1)/2;
} else if( vAlign == Alignment.Bottom ) {
y += (h-size) - (size+leading)*(lines-1);
}
}
y += ascent;
// calculate starting point for alignment
float paintX = x;
switch( hAlign ) {
case Right: {
paintX = x + w - textLayout.getVisibleAdvance();
break;
}
case Center: {
paintX = x + (w - textLayout.getVisibleAdvance())/2;
break;
}
}
// Draw line
textLayout.draw(g2d, paintX, y);
// Move down to top of next line
y += descent + leading;
i++;
}
相关的代码段如上所示。 attribText
之前是AttributtedString
。 context
是g2d.getFontRenderContext()
。
答案 0 :(得分:0)
这篇文章现在相当陈旧,所以我希望你找到一个适合你需求的解决方案。如果你还没有想到的话。您只需要绘制可见区域内的文本。由于您知道每行的y坐标,因此很容易检查y是否位于getVisibleRect()的范围内。只绘制必要的文本可以大大提高性能(假设您的文本当然比单个页面长)。