|
Spec-Zone .ru
спецификации, руководства, описания, API
|
public final class LineBreakMeasurer extends Object
LineBreakMeasurer class позволяет разработанному тексту быть поврежденным в строки (или сегменты) что подгонка в пределах определенного визуального усовершенствования. Это полезно для клиентов, которые хотят вывести на экран абзац текста, который соответствует в пределах определенного width, названного переносящимся width.
LineBreakMeasurer создается с iterator по стилизованному тексту. Диапазон iterator должен быть единственным абзацем в тексте. LineBreakMeasurer поддерживает позицию в тексте для запуска следующего текстового сегмента. Первоначально, эта позиция является запуском текста. Абзацы присваиваются полное направление (или слева направо или справа налево) согласно двунаправленным правилам форматирования. У всех сегментов, полученных из абзаца, есть то же самое направление как абзац.
Сегменты текста получаются, вызывая метод nextLayout, который возвращает a TextLayout представление текста, который соответствует в пределах переносящегося width. nextLayout метод перемещает текущую позицию до конца расположения, возвращенного из nextLayout.
LineBreakMeasurer реализует обычно используемую повреждающую строку политику: Каждое слово, которое соответствует в пределах переносящегося width, помещается в строку. Если первое слово не соответствует, то все символы, которые соответствуют в пределах переносящегося width, помещаются в строку. По крайней мере один символ помещается в каждую строку.
TextLayout экземпляры, возвращенные LineBreakMeasurer обработайте вкладки как 0-width пробелы. Клиенты, которые хотят получить разграниченные вкладкой сегменты для того, чтобы расположить, должны использовать перегрузку nextLayout который берет ограничивающее смещение в тексте. Ограничивающее смещение должно быть первым символом после вкладки. TextLayout объекты, возвращенные из этого метода, заканчиваются в обеспеченном пределе (или прежде, если текст между текущей позицией и пределом не будет соответствовать полностью в пределах переносящегося width).
Клиенты, которые размечают разграниченный вкладкой текст, нуждаются в немного отличающейся повреждающей строку политике после того, как первый сегмент был помещен в строку. Вместо того, чтобы приспособить частичные слова в остающемся пространстве, они должны поместить слова, которые не помещаются в остающееся пространство полностью на следующей строке. Это изменение политики можно требовать на перегрузке nextLayout который берет a boolean параметр. Если этот параметр true, nextLayout возвраты null если первое слово не будет помещаться в данное пространство. См. выборку вкладки ниже.
Вообще, если текст, используемый, чтобы создать LineBreakMeasurer изменения, новое LineBreakMeasurer должен быть создан, чтобы отразить изменение. (Старое LineBreakMeasurer продолжает функционировать должным образом, но это не будет знать о текстовом изменении.) Однако, если текстовое изменение является вставкой или удалением единственного символа, существующего LineBreakMeasurer может быть 'обновлен', вызывая insertChar или deleteChar. Обновление существующего LineBreakMeasurer намного быстрее чем создание нового. Клиенты, которые изменяют текст, основанный на пользователе, вводящем, должны использовать в своих интересах эти методы.
Примеры:
Рендеринг абзаца в компоненте
public void paint(Graphics graphics) {
Point2D pen = new Point2D(10, 20);
Graphics2D g2d = (Graphics2D)graphics;
FontRenderContext frc = g2d.getFontRenderContext();
// let styledText be an AttributedCharacterIterator containing at least
// one character
LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);
float wrappingWidth = getSize().width - 15;
while (measurer.getPosition() < fStyledText.length()) {
TextLayout layout = measurer.nextLayout(wrappingWidth);
pen.y += (layout.getAscent());
float dx = layout.isLeftToRight() ?
0 : (wrappingWidth - layout.getAdvance());
layout.draw(graphics, pen.x + dx, pen.y);
pen.y += layout.getDescent() + layout.getLeading();
}
}
Rendering text with tabs. For simplicity, the overall text direction is assumed to be left-to-right
public void paint(Graphics graphics) {
float leftMargin = 10, rightMargin = 310;
float[] tabStops = { 100, 250 };
// assume styledText is an AttributedCharacterIterator, and the number
// of tabs in styledText is tabCount
int[] tabLocations = new int[tabCount+1];
int i = 0;
for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
if (c == '\t') {
tabLocations[i++] = styledText.getIndex();
}
}
tabLocations[tabCount] = styledText.getEndIndex() - 1;
// Now tabLocations has an entry for every tab's offset in
// the text. For convenience, the last entry is tabLocations
// is the offset of the last character in the text.
LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
int currentTab = 0;
float verticalPos = 20;
while (measurer.getPosition() < styledText.getEndIndex Lay out and draw each line. All segments on a line must be computed before any drawing can occur since we must know the largest ascent on the line. TextLayouts are computed and stored in a Vector their horizontal positions are stored in a parallel Vector. lineContainsText is true after first segment is drawn boolean lineContainsText="false;" boolean lineComplete="false;" float maxAscent="0," maxDescent="0;" float horizontalPos="leftMargin;" Vector layouts="new" Vector 1 Vector penPositions="new" Vector 1 while lineComplete float wrappingWidth="rightMargin" - horizontalPos TextLayout layout="measurer.nextLayout(wrappingWidth," tabLocations currentTab 1 lineContainsText layout can be null if lineContainsText is true if layout ="null)" layouts.addElement layout penPositions.addElement new Float horizontalPos horizontalPos ="layout.getAdvance();" maxAscent="Math.max(maxAscent," layout.getAscent maxDescent="Math.max(maxDescent," layout.getDescent layout.getLeading else lineComplete="true;" lineContainsText="true;" if measurer.getPosition ="=" tabLocations currentTab 1 currentTab if measurer.getPosition ="=" styledText.getEndIndex lineComplete="true;" else if horizontalPos>= tabStops[tabStops.length-1])
lineComplete = true;
if (!lineComplete) {
// move to next tab stop
int j;
for (j=0; horizontalPos >= tabStops[j]; j++) {}
horizontalPos = tabStops[j];
}
}
verticalPos += maxAscent;
Enumeration layoutEnum = layouts.elements();
Enumeration positionEnum = penPositions.elements();
// now iterate through layouts and draw them
while (layoutEnum.hasMoreElements()) {
TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
Float nextPosition = (Float) positionEnum.nextElement();
nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
}
verticalPos += maxDescent;
}
}
TextLayout| Constructor and Description |
|---|
LineBreakMeasurer(AttributedCharacterIterator text,
BreakIterator breakIter,
FontRenderContext frc)
Constructs a
LineBreakMeasurer for the specified text. |
LineBreakMeasurer(AttributedCharacterIterator text,
FontRenderContext frc)
Constructs a
LineBreakMeasurer for the specified text. |
| Modifier and Type | Method and Description |
|---|---|
void |
deleteChar(AttributedCharacterIterator newParagraph,
int deletePos)
Updates this
LineBreakMeasurer after a single
character is deleted from the text, and sets the current
position to the beginning of the paragraph. |
int |
getPosition()
Returns the current position of this
LineBreakMeasurer. |
void |
insertChar(AttributedCharacterIterator newParagraph,
int insertPos)
Updates this
LineBreakMeasurer after a single
character is inserted into the text, and sets the current
position to the beginning of the paragraph. |
TextLayout |
nextLayout(float wrappingWidth)
Returns the next layout, and updates the current position.
|
TextLayout |
nextLayout(float wrappingWidth,
int offsetLimit,
boolean requireNextWord)
Returns the next layout, and updates the current position.
|
int |
nextOffset(float wrappingWidth)
Returns the position at the end of the next layout.
|
int |
nextOffset(float wrappingWidth,
int offsetLimit,
boolean requireNextWord)
Returns the position at the end of the next layout.
|
void |
setPosition(int newPosition)
Sets the current position of this
LineBreakMeasurer. |
public LineBreakMeasurer(AttributedCharacterIterator text, FontRenderContext frc)
LineBreakMeasurer for the specified text.text - the text for which this LineBreakMeasurer
produces TextLayout objects; the text must contain
at least one character; if the text available through
iter changes, further calls to this
LineBreakMeasurer instance are undefined (except,
in some cases, when insertChar or
deleteChar are invoked afterward - see below)frc - contains information about a graphics device which is
needed to measure the text correctly;
text measurements can vary slightly depending on the
device resolution, and attributes such as antialiasing; this
parameter does not specify a translation between the
LineBreakMeasurer and user spaceinsertChar(java.text.AttributedCharacterIterator, int),
deleteChar(java.text.AttributedCharacterIterator, int)public LineBreakMeasurer(AttributedCharacterIterator text, BreakIterator breakIter, FontRenderContext frc)
LineBreakMeasurer for the specified text.text - the text for which this LineBreakMeasurer
produces TextLayout objects; the text must contain
at least one character; if the text available through
iter changes, further calls to this
LineBreakMeasurer instance are undefined (except,
in some cases, when insertChar or
deleteChar are invoked afterward - see below)breakIter - the BreakIterator which defines line
breaksfrc - contains information about a graphics device which is
needed to measure the text correctly;
text measurements can vary slightly depending on the
device resolution, and attributes such as antialiasing; this
parameter does not specify a translation between the
LineBreakMeasurer and user spaceIllegalArgumentException - if the text has less than one characterinsertChar(java.text.AttributedCharacterIterator, int),
deleteChar(java.text.AttributedCharacterIterator, int)public int nextOffset(float wrappingWidth)
LineBreakMeasurer.wrappingWidth - the maximum visible advance permitted for
the text in the next layoutTextLayout.public int nextOffset(float wrappingWidth,
int offsetLimit,
boolean requireNextWord)
LineBreakMeasurer.wrappingWidth - the maximum visible advance permitted for
the text in the next layoutoffsetLimit - the first character that can not be included
in the next layout, even if the text after the limit would fit
within the wrapping width; offsetLimit must be
greater than the current positionrequireNextWord - if true, the current position
that is returned if the entire next word does not fit within
wrappingWidth; if false, the offset
returned is at least one greater than the current positionTextLayoutpublic TextLayout nextLayout(float wrappingWidth)
wrappingWidth - the maximum visible advance permitted for
the text in the next layoutTextLayout, beginning at the current
position, which represents the next line fitting within
wrappingWidthpublic TextLayout nextLayout(float wrappingWidth, int offsetLimit, boolean requireNextWord)
wrappingWidth - the maximum visible advance permitted
for the text in the next layoutoffsetLimit - the first character that can not be
included in the next layout, even if the text after the limit
would fit within the wrapping width; offsetLimit
must be greater than the current positionrequireNextWord - if true, and if the entire word
at the current position does not fit within the wrapping width,
null is returned. If false, a valid
layout is returned that includes at least the character at the
current positionTextLayout, beginning at the current
position, that represents the next line fitting within
wrappingWidth. If the current position is at the end
of the text used by this LineBreakMeasurer,
null is returnedpublic int getPosition()
LineBreakMeasurer.LineBreakMeasurersetPosition(int)public void setPosition(int newPosition)
LineBreakMeasurer.newPosition - the current position of this
LineBreakMeasurer; the position should be within the
text used to construct this LineBreakMeasurer (or in
the text most recently passed to insertChar
or deleteChargetPosition()public void insertChar(AttributedCharacterIterator newParagraph, int insertPos)
LineBreakMeasurer after a single
character is inserted into the text, and sets the current
position to the beginning of the paragraph.newParagraph - the text after the insertioninsertPos - the position in the text at which the character
is insertedIndexOutOfBoundsException - if insertPos is less
than the start of newParagraph or greater than
or equal to the end of newParagraphNullPointerException - if newParagraph is
nulldeleteChar(java.text.AttributedCharacterIterator, int)public void deleteChar(AttributedCharacterIterator newParagraph, int deletePos)
LineBreakMeasurer after a single
character is deleted from the text, and sets the current
position to the beginning of the paragraph.newParagraph - the text after the deletiondeletePos - the position in the text at which the character
is deletedIndexOutOfBoundsException - if deletePos is
less than the start of newParagraph or greater
than the end of newParagraphNullPointerException - if newParagraph is
nullinsertChar(java.text.AttributedCharacterIterator, int)
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2013, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b92