Java Code Examples for java.awt.font.LineBreakMeasurer#setPosition()

The following examples show how to use java.awt.font.LineBreakMeasurer#setPosition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Test.java    From tribaltrouble with GNU General Public License v2.0 6 votes vote down vote up
private final static void pixelDataFromString(int width, int height, String str, java.awt.Font font, int[] pixels, LineBreakMeasurer measurer) {
	measurer.setPosition(0);
	g2d.clearRect(0, 0, width, height);
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	float wrapping_width = width;
	float y = 0;
	int length = str.length();
	while (measurer.getPosition() < length) {
		TextLayout layout = measurer.nextLayout(wrapping_width);
		y += (layout.getAscent());
		float x = layout.isLeftToRight() ? 0 : (wrapping_width - layout.getAdvance());

		layout.draw(g2d, x, y);
		y += layout.getDescent() + layout.getLeading();
	}
	image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), pixels);
}
 
Example 2
Source File: WordBreakingLineIterator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private TextLayout performWordBreak( final int start, final TextLayout textLayout,
    final LineBreakMeasurer lineBreakMeasurer, final int end ) {
  final TextLayout layout;
  if ( wordInstance.isBoundary( end ) != false ) {
    return textLayout;
  }

  int preceding = wordInstance.preceding( end );
  if ( preceding == start ) {
    // single word does not fit on the line, so print full word
    lineBreakMeasurer.setPosition( start );
    return lineBreakMeasurer.nextLayout( INFINITY, wordInstance.following( end ), false );
  } else {
    lineBreakMeasurer.setPosition( start );
    return lineBreakMeasurer.nextLayout( INFINITY, preceding, false );
  }
}
 
Example 3
Source File: TestLineBreakWithFontSub.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void test() {

        // construct a paragraph as follows: MIXED + [SPACING + WORD] + ...
        StringBuffer text = new StringBuffer(MIXED);
        for (int i=0; i < NUM_WORDS; i++) {
            text.append(SPACING);
            text.append(WORD);
        }

        AttributedString attrString = new AttributedString(text.toString());
        attrString.addAttribute(TextAttribute.SIZE, new Float(24.0));

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(),
                                                           DEFAULT_FRC);

        // get width of a space-word sequence, in context
        int sequenceLength = WORD.length()+SPACING.length();
        measurer.setPosition(text.length() - sequenceLength);

        TextLayout layout = measurer.nextLayout(10000.0f);

        if (layout.getCharacterCount() != sequenceLength) {
            throw new Error("layout length is incorrect!");
        }

        final float sequenceAdvance = layout.getVisibleAdvance();

        float wrappingWidth = sequenceAdvance * 2;

        // now run test with a variety of widths
        while (wrappingWidth < (sequenceAdvance*NUM_WORDS)) {
            measurer.setPosition(0);
            checkMeasurer(measurer,
                          wrappingWidth,
                          sequenceAdvance,
                          text.length());
            wrappingWidth += sequenceAdvance / 5;
        }
    }
 
Example 4
Source File: TestLineBreakWithFontSub.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void test() {

        // construct a paragraph as follows: MIXED + [SPACING + WORD] + ...
        StringBuffer text = new StringBuffer(MIXED);
        for (int i=0; i < NUM_WORDS; i++) {
            text.append(SPACING);
            text.append(WORD);
        }

        AttributedString attrString = new AttributedString(text.toString());
        attrString.addAttribute(TextAttribute.SIZE, new Float(24.0));

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(),
                                                           DEFAULT_FRC);

        // get width of a space-word sequence, in context
        int sequenceLength = WORD.length()+SPACING.length();
        measurer.setPosition(text.length() - sequenceLength);

        TextLayout layout = measurer.nextLayout(10000.0f);

        if (layout.getCharacterCount() != sequenceLength) {
            throw new Error("layout length is incorrect!");
        }

        final float sequenceAdvance = layout.getVisibleAdvance();

        float wrappingWidth = sequenceAdvance * 2;

        // now run test with a variety of widths
        while (wrappingWidth < (sequenceAdvance*NUM_WORDS)) {
            measurer.setPosition(0);
            checkMeasurer(measurer,
                          wrappingWidth,
                          sequenceAdvance,
                          text.length());
            wrappingWidth += sequenceAdvance / 5;
        }
    }
 
Example 5
Source File: TextArea.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 6
Source File: TextArea.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale * Integer.parseInt(element.getAttribute("size")))));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 7
Source File: DrawTextParagraph.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * break text into lines, each representing a line of text that fits in the wrapping width
 *
 * @param graphics The drawing context for computing text-lengths.
 */
protected void breakText(Graphics2D graphics){
    lines.clear();

    DrawFactory fact = DrawFactory.getInstance(graphics);
    fact.fixFonts(graphics);
    StringBuilder text = new StringBuilder();
    AttributedString at = getAttributedString(graphics, text);
    boolean emptyParagraph = ("".equals(text.toString().trim()));

    AttributedCharacterIterator it = at.getIterator();
    LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext());
    for (;;) {
        int startIndex = measurer.getPosition();

        // add a pixel to compensate rounding errors
        double wrappingWidth = getWrappingWidth(lines.isEmpty(), graphics) + 1;
        // shape width can be smaller that the sum of insets (this was proved by a test file)
        if(wrappingWidth < 0) {
            wrappingWidth = 1;
        }

        int nextBreak = text.indexOf("\n", startIndex + 1);
        if (nextBreak == -1) {
            nextBreak = it.getEndIndex();
        }

        TextLayout layout = measurer.nextLayout((float)wrappingWidth, nextBreak, true);
        if (layout == null) {
             // layout can be null if the entire word at the current position
             // does not fit within the wrapping width. Try with requireNextWord=false.
             layout = measurer.nextLayout((float)wrappingWidth, nextBreak, false);
        }

        if(layout == null) {
            // exit if can't break any more
            break;
        }

        int endIndex = measurer.getPosition();
        // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n)
        if(endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n'){
            measurer.setPosition(endIndex + 1);
        }

        TextAlign hAlign = paragraph.getTextAlign();
        if(hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) {
            layout = layout.getJustifiedLayout((float)wrappingWidth);
        }

        AttributedString str = (emptyParagraph)
            ? null // we will not paint empty paragraphs
            : new AttributedString(it, startIndex, endIndex);
        DrawTextFragment line = fact.getTextFragment(layout, str);
        lines.add(line);

        maxLineHeight = Math.max(maxLineHeight, line.getHeight());

        if(endIndex == it.getEndIndex()) {
            break;
        }
    }

    rawText = text.toString();
}
 
Example 8
Source File: OracleText.java    From magarena with GNU General Public License v3.0 4 votes vote down vote up
private static SortedMap<Float, TextLayout> tryTextLayout(
    AttributedString attrString,
    FontRenderContext frc,
    Rectangle box,
    int leftPadding,
    int topPadding
) {
    final SortedMap<Float, TextLayout> lines = new TreeMap<>();
    AttributedCharacterIterator text = attrString.getIterator();
    int paragraphStart = text.getBeginIndex();
    int paragraphEnd = text.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(text, frc);
    float boxWidth = (float)box.getWidth();
    float boxHeight = (float)box.getHeight();
    float posY = topPadding;
    lineMeasurer.setPosition(paragraphStart);

    //Measure length of string to fit in box
    final AttributedCharacterIterator iter = attrString.getIterator();
    while (lineMeasurer.getPosition() < paragraphEnd) {
        //Check for ptPanel overlap
        int next = lineMeasurer.nextOffset(posY >= 123 ? boxWidth - (leftPadding << 1) - 100 : boxWidth - (leftPadding << 1));
        int limit = next;
        //Check for newlines
        for (int i = lineMeasurer.getPosition(); i < next; ++i) {
            char c = iter.setIndex(i);
            if (c == NEWLINE && i > lineMeasurer.getPosition()) {
                limit = i;
                break;
            }
        }

        //get+draw measured length
        TextLayout layout = lineMeasurer.nextLayout(boxWidth, limit, false);
        posY += layout.getAscent();
        lines.put(posY, layout);

        //add extra space between paragraphs
        if (limit < next) {
            posY += layout.getLeading() + layout.getDescent();
        }

        //move to next line
        posY += layout.getDescent();

        //check if out of room
        if (posY > boxHeight) {
            lines.clear();
            break;
        }
    }
    return lines;
}
 
Example 9
Source File: TextArea2.java    From pdfxtk with Apache License 2.0 4 votes vote down vote up
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     
     // java 5: Float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale * fontSize)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     
     //style.fontSize = Float.parseFloat(element.getAttribute("font-size"));
     //style.setParam(context, this, element.getAttribute("font-size"));
    // this.style("fontsize", element.getAttribute("font-size"));
     
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }