我正在使用Java2D的TextLayout类,结合LineBreakMeasurer和AttributedCharacterIterator将一段文本绘制到一个框中。文本已经被换行了。
分析表明代码非常慢,大部分时间都花费在TextLayout.draw(..)方法上。
有没有人有加速改进的建议?
上面显示了相关的代码片段。attribText是先设置好的AttributtedString。context是g2d.getFontRenderContext()。
分析表明代码非常慢,大部分时间都花费在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()。
TextLayout.draw()
隐式调用了drawGlyphVector()
,这是耗时的部分。也许真正的问题是:如何使用Java2D绘制自动换行的文本,避免使用TextLayout
,而是使用drawString()
呢? - kongo09