Example usage for java.awt.font TextLayout getAdvance

List of usage examples for java.awt.font TextLayout getAdvance

Introduction

In this page you can find the example usage for java.awt.font TextLayout getAdvance.

Prototype

public float getAdvance() 

Source Link

Document

Returns the advance of this TextLayout .

Usage

From source file:ShowOff.java

protected float drawBoxedString(Graphics2D g2, String s, Color c1, Color c2, double x) {
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout subLayout = new TextLayout(s, mFont, frc);
    float advance = subLayout.getAdvance();

    GradientPaint gradient = new GradientPaint((float) x, 0, c1, (float) (x + advance), 0, c2);
    g2.setPaint(gradient);/* ww  w .  jav  a  2  s.  c om*/
    Rectangle2D bounds = mLayout.getBounds();
    Rectangle2D back = new Rectangle2D.Double(x, 0, advance, bounds.getHeight());
    g2.fill(back);

    g2.setPaint(Color.white);
    g2.setFont(mFont);
    g2.drawString(s, (float) x, (float) -bounds.getY());
    return advance;
}

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  va2 s.com*/
 * @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:MainClass.java

public void paint(Graphics g) {
    Dimension size = getSize();/*from  w ww.  j a  v  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:LineBreakSample.java

public void paintComponent(Graphics g) {

    super.paintComponent(g);
    setBackground(Color.white);/*from  w w w .  j  a  v a2 s  .  co  m*/

    Graphics2D graphics2D = (Graphics2D) g;

    // Set formatting width to width of Component.
    Dimension size = getSize();
    float formatWidth = (float) size.width;

    float drawPosY = 0;

    lineMeasurer.setPosition(paragraphStart);

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

        // Retrieve next layout.
        TextLayout layout = lineMeasurer.nextLayout(formatWidth);
        // 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 = formatWidth - layout.getAdvance();
        }

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

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

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

/**
 * Create an image that contains text/*from   w w  w .j  av a  2s . 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  w w w . j  a v a2  s.  c o  m*/
    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.pentaho.reporting.engine.classic.core.layout.process.text.ComplexTextMinorAxisLayoutStep.java

private RenderBox generateLine(final ParagraphRenderBox paragraph, final ParagraphPoolBox lineBoxContainer,
        final RenderableComplexText text, final double height, final ParagraphFontMetricsImpl metrics) {
    // derive a new RenderableComplexText object representing the line, that holds on to the TextLayout class.
    TextLayout textLayout = text.getTextLayout();

    // Store the height and width, so that the other parts of the layouter have access to the information
    // text.setCachedHeight();
    text.setCachedHeight(Math.max(StrictGeomUtility.toInternalValue(height), lineBoxContainer.getLineHeight()));
    text.setCachedWidth(StrictGeomUtility.toInternalValue(textLayout.getAdvance()));
    text.setParagraphFontMetrics(metrics);

    MinorAxisNodeContext nodeContext = getNodeContext();
    final long alignmentX = RenderUtility.computeHorizontalAlignment(paragraph.getTextAlignment(),
            nodeContext.getContentAreaWidth(), StrictGeomUtility.toInternalValue(textLayout.getAdvance()));
    text.setCachedX(alignmentX + nodeContext.getX());

    // Create a shallow copy of the paragraph-pool to act as a line container.
    final RenderBox line = (RenderBox) paragraph.getPool().deriveFrozen(false);
    line.addGeneratedChild(text);//from w  w  w . j  a  va 2  s. c om

    // Align the line inside the paragraph. (Adjust the cachedX position depending on whether the line is left,
    // centred or right aligned)
    line.setCachedX(alignmentX + nodeContext.getX());
    line.setCachedWidth(nodeContext.getContentAreaWidth());
    return line;
}

From source file:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a column and return the result
 *
 * @param sheet the sheet to calculate/*w ww .  ja  v  a 2s .co m*/
 * @param column    0-based index of the column
 * @param useMergedCells    whether to use merged cells
 * @return  the width in pixels
 */
public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells) {
    AttributedString str;
    TextLayout layout;

    Workbook wb = sheet.getWorkbook();
    DataFormatter formatter = new DataFormatter(ZssContext.getCurrent().getLocale(), false); //20111227, henrichen@zkoss.org
    Font defaultFont = wb.getFontAt((short) 0);

    str = new AttributedString(String.valueOf(defaultChar));
    copyAttributes(defaultFont, str, 0, 1);
    layout = new TextLayout(str.getIterator(), fontRenderContext);
    int defaultCharWidth = (int) layout.getAdvance();

    double width = -1;
    for (Row row : sheet) {
        Cell cell = row.getCell(column);

        if (cell == null) {
            continue;
        }

        double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
        width = Math.max(width, cellWidth);
    }
    return width;
}

From source file:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a column based on a subset of the rows and return the result
 *
 * @param sheet the sheet to calculate/*from w ww.  j  av a  2s  . c  o  m*/
 * @param column    0-based index of the column
 * @param useMergedCells    whether to use merged cells
 * @param firstRow  0-based index of the first row to consider (inclusive)
 * @param lastRow   0-based index of the last row to consider (inclusive)
 * @return  the width in pixels
 */
public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells, int firstRow,
        int lastRow) {
    AttributedString str;
    TextLayout layout;

    Workbook wb = sheet.getWorkbook();
    DataFormatter formatter = new DataFormatter(ZssContext.getCurrent().getLocale(), false); //20111227, henrichen@zkoss.org: ZSS-68
    Font defaultFont = wb.getFontAt((short) 0);

    str = new AttributedString(String.valueOf(defaultChar));
    copyAttributes(defaultFont, str, 0, 1);
    layout = new TextLayout(str.getIterator(), fontRenderContext);
    int defaultCharWidth = (int) layout.getAdvance();

    double width = -1;
    for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) {
        Row row = sheet.getRow(rowIdx);
        if (row != null) {

            Cell cell = row.getCell(column);

            if (cell == null) {
                continue;
            }

            double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
            width = Math.max(width, cellWidth);
        }
    }
    return width;
}