Example usage for java.text AttributedCharacterIterator getBeginIndex

List of usage examples for java.text AttributedCharacterIterator getBeginIndex

Introduction

In this page you can find the example usage for java.text AttributedCharacterIterator getBeginIndex.

Prototype

public int getBeginIndex();

Source Link

Document

Returns the start index of the text.

Usage

From source file:Main.java

/**
 * Returns the {@link Dimension} for the given {@link JTextComponent}
 * subclass that will show the whole word wrapped text in the given width.
 * It won't work for styled text of varied size or style, it's assumed that
 * the whole text is rendered with the {@link JTextComponent}s font.
 *
 * @param textComponent the {@link JTextComponent} to calculate the {@link Dimension} for
 * @param width the width of the resulting {@link Dimension}
 * @param text the {@link String} which should be word wrapped
 * @return The calculated {@link Dimension}
 *///from  w  w w  . ja  v  a2  s .co m
public static Dimension getWordWrappedTextDimension(JTextComponent textComponent, int width, String text) {
    if (textComponent == null) {
        throw new IllegalArgumentException("textComponent cannot be null");
    }
    if (width < 1) {
        throw new IllegalArgumentException("width must be 1 or greater");
    }
    if (text == null) {
        text = textComponent.getText();
    }
    if (text.isEmpty()) {
        return new Dimension(width, 0);
    }

    FontMetrics metrics = textComponent.getFontMetrics(textComponent.getFont());
    FontRenderContext rendererContext = metrics.getFontRenderContext();
    float formatWidth = width - textComponent.getInsets().left - textComponent.getInsets().right;

    int lines = 0;
    String[] paragraphs = text.split("\n");
    for (String paragraph : paragraphs) {
        if (paragraph.isEmpty()) {
            lines++;
        } else {
            AttributedString attributedText = new AttributedString(paragraph);
            attributedText.addAttribute(TextAttribute.FONT, textComponent.getFont());
            AttributedCharacterIterator charIterator = attributedText.getIterator();
            LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIterator, rendererContext);

            lineMeasurer.setPosition(charIterator.getBeginIndex());
            while (lineMeasurer.getPosition() < charIterator.getEndIndex()) {
                lineMeasurer.nextLayout(formatWidth);
                lines++;
            }
        }
    }

    return new Dimension(width,
            metrics.getHeight() * lines + textComponent.getInsets().top + textComponent.getInsets().bottom);
}

From source file:Utils.java

/** 
 * Renders a paragraph of text (line breaks ignored) to an image (created and returned). 
 *
 * @param font The font to use/*w  ww.j  a va2s. c  om*/
 * @param textColor The color of the text
 * @param text The message
 * @param width The width the text should be limited to
 * @return An image with the text rendered into it
 */
public static BufferedImage renderTextToImage(Font font, Color textColor, String text, int width) {
    Hashtable map = new Hashtable();
    map.put(TextAttribute.FONT, font);
    AttributedString attributedString = new AttributedString(text, map);
    AttributedCharacterIterator paragraph = attributedString.getIterator();

    FontRenderContext frc = new FontRenderContext(null, false, false);
    int paragraphStart = paragraph.getBeginIndex();
    int paragraphEnd = paragraph.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

    float drawPosY = 0;

    //First time around, just determine the height
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move it down
        drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading();
    }

    BufferedImage image = createCompatibleImage(width, (int) drawPosY);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawPosY = 0;
    lineMeasurer.setPosition(paragraphStart);
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move y-coordinate by the ascent of the layout.
        drawPosY += layout.getAscent();

        /* Compute pen x position.  If the paragraph is
           right-to-left, we want to align the TextLayouts
           to the right edge of the panel.
         */
        float drawPosX;
        if (layout.isLeftToRight()) {
            drawPosX = 0;
        } else {
            drawPosX = width - layout.getAdvance();
        }

        // Draw the TextLayout at (drawPosX, drawPosY).
        layout.draw(graphics, drawPosX, drawPosY);

        // Move y-coordinate in preparation for next layout.
        drawPosY += layout.getDescent() + layout.getLeading();
    }

    graphics.dispose();
    return image;
}

From source file:Main.java

/**
 * Serialises an <code>AttributedString</code> object.
 *
 * @param as  the attributed string object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 *///  ww  w .j a  v a  2 s .  c o m
public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (as != null) {
        stream.writeBoolean(false);
        AttributedCharacterIterator aci = as.getIterator();
        // build a plain string from aci
        // then write the string
        StringBuffer plainStr = new StringBuffer();
        char current = aci.first();
        while (current != CharacterIterator.DONE) {
            plainStr = plainStr.append(current);
            current = aci.next();
        }
        stream.writeObject(plainStr.toString());

        // then write the attributes and limits for each run
        current = aci.first();
        int begin = aci.getBeginIndex();
        while (current != CharacterIterator.DONE) {
            // write the current character - when the reader sees that this
            // is not CharacterIterator.DONE, it will know to read the
            // run limits and attributes
            stream.writeChar(current);

            // now write the limit, adjusted as if beginIndex is zero
            int limit = aci.getRunLimit();
            stream.writeInt(limit - begin);

            // now write the attribute set
            Map atts = new HashMap(aci.getAttributes());
            stream.writeObject(atts);
            current = aci.setIndex(limit);
        }
        // write a character that signals to the reader that all runs
        // are done...
        stream.writeChar(CharacterIterator.DONE);
    } else {
        // write a flag that indicates a null
        stream.writeBoolean(true);
    }

}

From source file:LineBreakSample.java

public LineBreakSample() {
    AttributedCharacterIterator paragraph = vanGogh.getIterator();
    paragraphStart = paragraph.getBeginIndex();
    paragraphEnd = paragraph.getEndIndex();

    // Create a new LineBreakMeasurer from the paragraph.
    lineMeasurer = new LineBreakMeasurer(paragraph, new FontRenderContext(null, false, false));
}

From source file:MainClass.java

public void paint(Graphics g) {
    Dimension size = getSize();//w ww . j  av a2 s .  c o  m

    String s = "To java2s.com or not to java2s.com, that is a question";

    Hashtable map = new Hashtable();
    map.put(TextAttribute.SIZE, new Float(32.0f));

    AttributedString as = new AttributedString(s, map);

    map = new Hashtable();
    map.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);

    as.addAttributes(map, 33, 52);

    AttributedCharacterIterator aci = as.getIterator();

    int startIndex = aci.getBeginIndex();
    int endIndex = aci.getEndIndex();

    LineBreakMeasurer measurer;
    measurer = new LineBreakMeasurer(aci, new FontRenderContext(null, false, false));
    measurer.setPosition(startIndex);

    float wrappingWidth = (float) size.width;

    float Y = 0.0f;

    while (measurer.getPosition() < endIndex) {
        TextLayout layout = measurer.nextLayout(wrappingWidth);

        Y += layout.getAscent();

        float X = 0.0f;

        switch (justify) {
        case LEFT:
            if (layout.isLeftToRight())
                X = 0.0f;
            else
                X = wrappingWidth - layout.getAdvance();
            break;

        case RIGHT:
            if (layout.isLeftToRight())
                X = wrappingWidth - layout.getVisibleAdvance();
            else
                X = wrappingWidth;
            break;

        case CENTER:
            if (layout.isLeftToRight())
                X = (wrappingWidth - layout.getVisibleAdvance()) / 2;
            else
                X = (wrappingWidth + layout.getAdvance()) / 2 - layout.getAdvance();
            break;

        case EQUALITY:
            layout = layout.getJustifiedLayout(wrappingWidth);
        }

        layout.draw((Graphics2D) g, X, Y);

        Y += layout.getDescent() + layout.getLeading();
    }
}

From source file:com.sander.verhagen.frame.LineWrapCellRenderer.java

private int getLineCount(JTextArea textArea) {
    AttributedString string = new AttributedString(textArea.getText());
    FontRenderContext fontRenderContext = textArea.getFontMetrics(textArea.getFont()).getFontRenderContext();
    AttributedCharacterIterator characterIterator = string.getIterator();
    LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(characterIterator, fontRenderContext);
    lineBreakMeasurer.setPosition(characterIterator.getBeginIndex());

    int lineCount = 0;
    while (lineBreakMeasurer.getPosition() < characterIterator.getEndIndex()) {
        lineBreakMeasurer.nextLayout(textArea.getSize().width);
        lineCount++;//from  w ww  .  jav a  2  s  .c o  m
    }
    return lineCount;
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create an image that contains text//w  ww. j  a  va  2  s  .c  o m
 * 
 * @param height
 * @param width
 * @param text
 * @param textColor
 * @param center
 * @param fontMap
 * @param type
 * @return
 */
private BufferedImage createText(int height, int width, String text, String textColor, boolean center,
        Map<TextAttribute, Object> fontMap, int type) {
    BufferedImage img = new BufferedImage(width, height, type);
    Graphics2D g2d = null;
    try {
        g2d = (Graphics2D) img.getGraphics();

        // Create attributed text
        AttributedString txt = new AttributedString(text, fontMap);

        // Set graphics color
        g2d.setColor(Color.decode(textColor));

        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        AttributedCharacterIterator paragraph = txt.getIterator();
        int paragraphStart = paragraph.getBeginIndex();
        int paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2d.getFontRenderContext();
        LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

        // Set break width to width of Component.
        float breakWidth = (float) width;
        float drawPosY = 0;
        // Set position to the index of the first character in the
        // paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {
            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: drawPosX is always where the LEFT of the text is
            // placed.
            float drawPosX = layout.isLeftToRight() ? 0 : breakWidth - layout.getAdvance();

            if (center == true) {
                double xOffSet = (width - layout.getBounds().getWidth()) / 2;
                drawPosX = drawPosX + new Float(xOffSet);
            }

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2d, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } finally {
        if (g2d != null) {
            g2d.dispose();
        }
    }
    return img;
}

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

public void drawString(Graphics g, String text, RectangularShape bounds, Align align, double angle,
        boolean multiline) {
    Graphics2D g2 = (Graphics2D) g;
    Font font = g2.getFont();//from  ww  w .  j av  a 2 s. c  om
    if (angle != 0) {
        g2.setFont(font.deriveFont(AffineTransform.getRotateInstance(Math.toRadians(angle))));
    }

    Rectangle2D sSize = g2.getFontMetrics().getStringBounds(text, g2);
    Point2D pos = getPoint(bounds, align);
    double x = pos.getX();
    double y = pos.getY() + sSize.getHeight();

    switch (align) {
    case TopCenter:
    case BottomCenter:
    case Center:
        x -= (sSize.getWidth() / 2);
        break;
    case TopRight:
    case MiddleRight:
    case BottomRight:
        x -= (sSize.getWidth());
        break;
    case BottomLeft:
    case MiddleLeft:
    case TopLeft:
        break;
    }
    if (multiline) {
        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        //if (lineMeasurer == null) {
        AttributedCharacterIterator paragraph = new AttributedString(text).getIterator();
        paragraphStart = paragraph.getBeginIndex();
        paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2.getFontRenderContext();
        lineMeasurer = new LineBreakMeasurer(paragraph, frc);
        //}

        // Set break width to width of Component.
        float breakWidth = (float) bounds.getWidth();
        float drawPosY = (float) y;
        // Set position to the index of the first character in the paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {

            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: this won't occur for the English text in this sample.
            // Note: drawPosX is always where the LEFT of the text is placed.
            float drawPosX = layout.isLeftToRight() ? (float) x : (float) x + breakWidth - layout.getAdvance();

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } else {
        g2.drawString(text, (float) x, (float) y);
    }
    g2.setFont(font);
}

From source file:org.jfree.experimental.swt.SWTGraphics2D.java

/**
 * Draws a string at the specified position.
 *
 * @param iterator  the string./*from   w  w  w . ja v a  2s  . c  o  m*/
 * @param x  the x-coordinate.
 * @param y  the y-coordinate.
 */
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
    // for now we simply want to extract the chars from the iterator
    // and call an unstyled text renderer
    StringBuffer sb = new StringBuffer();
    int numChars = iterator.getEndIndex() - iterator.getBeginIndex();
    char c = iterator.first();
    for (int i = 0; i < numChars; i++) {
        sb.append(c);
        c = iterator.next();
    }
    drawString(new String(sb), x, y);
}

From source file:org.apache.fop.svg.AbstractFOPTextPainter.java

/**
 * Extract the raw text from an ACI./*from   www.  ja  va2 s  .c o  m*/
 * @param aci ACI to inspect
 * @return the extracted text
 */
protected String getText(AttributedCharacterIterator aci) {
    StringBuffer sb = new StringBuffer(aci.getEndIndex() - aci.getBeginIndex());
    for (char c = aci.first(); c != CharacterIterator.DONE; c = aci.next()) {
        sb.append(c);
    }
    return sb.toString();
}