Example usage for java.awt.font TextLayout getBounds

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

Introduction

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

Prototype

public Rectangle2D getBounds() 

Source Link

Document

Returns the bounds of this TextLayout .

Usage

From source file:Main.java

/**
 * Returns the bounds of the given string.
 *
 * @param text the string to measure//w  ww.j  a  v a  2  s.c  o  m
 * @return the bounds of the given string
 */
public static Rectangle2D getDefaultStringSize(String text) {
    Font font = UIManager.getFont("Label.font");
    FontRenderContext frc = new FontRenderContext(null, true, false);
    TextLayout layout = new TextLayout(text, font, frc);

    return layout.getBounds();
}

From source file:Main.java

/**
 * Creates and returns image from the given text.
 * @param text input text/*from w  w w . j  av  a  2s.c o m*/
 * @param font text font
 * @return image with input text
 */
public static BufferedImage createImageFromText(String text, Font font) {
    //You may want to change these setting, or make them parameters
    boolean isAntiAliased = true;
    boolean usesFractionalMetrics = false;
    FontRenderContext frc = new FontRenderContext(null, isAntiAliased, usesFractionalMetrics);
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D bounds = layout.getBounds();
    int w = (int) Math.ceil(bounds.getWidth());
    int h = (int) Math.ceil(bounds.getHeight()) + 2;
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); //for example;
    Graphics2D g = image.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, w, h);
    g.setColor(Color.BLACK);
    g.setFont(font);
    Object antiAliased = isAntiAliased ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
            : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antiAliased);
    Object fractionalMetrics = usesFractionalMetrics ? RenderingHints.VALUE_FRACTIONALMETRICS_ON
            : RenderingHints.VALUE_FRACTIONALMETRICS_OFF;
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics);
    g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY());
    g.dispose();

    return image;
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image./*  ww  w  .  ja va  2s.c  o m*/
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

From source file:piramide.interaction.reasoner.FuzzyReasonerWizardFacade.java

private BufferedImage createErrorMessagesImage(String text) {
    final Font font = TextTitle.DEFAULT_FONT;
    final Font bigBold = new Font(font.getName(), Font.BOLD, 24);
    final FontRenderContext frc = new FontRenderContext(null, true, false);
    final TextLayout layout = new TextLayout(text, bigBold, frc);
    final Rectangle2D bounds = layout.getBounds();
    final int w = (int) Math.ceil(bounds.getWidth());
    final int h = (int) Math.ceil(bounds.getHeight());
    final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    final Graphics2D g = image.createGraphics();
    g.setColor(Color.WHITE);/*w w  w. j  ava  2s  .com*/
    g.fillRect(0, 0, w, h);
    g.setColor(Color.RED);
    g.setFont(bigBold);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
    g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY());
    g.dispose();
    return image;
}

From source file:AnimatedMessagePanel.java

public void printMessages() {

    try {//w  ww  . ja va  2 s.  co  m
        Runnable runner = new Runnable() {
            public void run() {

                AnimatedMessagePanel.getInstance().setCurrentlyScrolling(true);
                Graphics2D g2 = (Graphics2D) og;

                int linecount = 1;
                StringTokenizer st1 = new StringTokenizer(messageQue[0]);
                String text1 = "";
                String testtext1 = "";
                String prodtext1 = "";
                while (st1.hasMoreTokens()) {
                    text1 = st1.nextToken();
                    testtext1 += text1 + " ";
                    FontRenderContext frc1 = g2.getFontRenderContext();
                    TextLayout t11 = new TextLayout(testtext1, font, frc1);
                    int sw1 = (int) t11.getBounds().getWidth();
                    if (sw1 > (getWidth() - 40)) {
                        linecount++;
                        testtext1 = "";
                        prodtext1 = text1;
                    } else
                        prodtext1 += text1 + " ";
                }

                for (int k = -(15) * (linecount - 1); k <= 15; k++) {
                    paintBG();
                    int y = k;
                    og.setColor(Color.black);
                    for (int j = 0; j < messageQue.length; j++) {
                        if (messageQue[j].length() != 0) {
                            StringTokenizer st = new StringTokenizer(messageQue[j]);
                            String text = "";
                            String testtext = "";
                            String prodtext = "";
                            while (st.hasMoreTokens()) {
                                text = st.nextToken();
                                testtext += text + " ";
                                FontRenderContext frc = g2.getFontRenderContext();
                                TextLayout t1 = new TextLayout(testtext, font, frc);
                                int sw = (int) t1.getBounds().getWidth();
                                if (sw > (getWidth() - 40)) {
                                    og.drawString(prodtext, 10, y);
                                    y += 12;
                                    testtext = "";
                                    prodtext = text;
                                } else
                                    prodtext += text + " ";
                            }
                            og.drawString(prodtext, 10, y);
                            y += 18;
                            if (y > getHeight())
                                break;
                        }
                    }
                    repaint();
                    try {
                        Thread.sleep(50);
                    } catch (Exception de) {
                    }
                }
                AnimatedMessagePanel.getInstance().setCurrentlyScrolling(false);
                AnimatedMessagePanel.getInstance().checkForMessagesWaiting();

            }
        };
        new Thread(runner, "printMessage.run").start();
    } catch (Exception e) {
    }
}

From source file:com.neophob.sematrix.core.generator.Textwriter.java

/**
 * create image.//from w  w  w .  j av a2s  .co m
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    //head and tailing space
    maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize;
    int ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY);
    g2 = img.createGraphics();

    g2.setColor(new Color(128));
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);

    g2.drawString(text, internalBufferXSize, ypos);
    DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer();
    byte[] textBuffer = dbi.getData();
    g2.dispose();

    xofs = 0;

    textAsImage = new int[maxXPos * internalBufferYSize];
    for (int i = 0; i < textAsImage.length; i++) {
        if (textBuffer[i] > 10) {
            textAsImage[i] = 127;
        } else {
            textAsImage[i] = 0;
        }
    }

    //clear internalbuffer
    Arrays.fill(this.internalBuffer, 0);
}

From source file:com.atlassian.theplugin.idea.bamboo.tree.BuildTreeNode.java

private void recalculateColumnWidths(final BuildListModel buildModel) {
    JLabel l = new JLabel();

    reasonWidth = 0.0;//from  w w w . j  a v  a 2 s . c  om
    serverWidth = 0.0;
    dateWidth = 0.0;
    planInProgressWidth = 0.0;

    for (BambooBuildAdapter b : buildModel.getBuilds()) {
        // PL-1202 - argument to TextLayout must be a non-empty string
        String reason = getBuildReasonString(b);
        TextLayout layoutStatus = new TextLayout(reason.length() > 0 ? reason : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        reasonWidth = Math.max(layoutStatus.getBounds().getWidth(), reasonWidth);
        String server = getBuildServerString(b);
        TextLayout layoutName = new TextLayout(server.length() > 0 ? server : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        serverWidth = Math.max(layoutName.getBounds().getWidth(), serverWidth);
        String date = getRelativeBuildTimeString(b);
        TextLayout layoutDate = new TextLayout(date.length() > 0 ? date : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        dateWidth = Math.max(layoutDate.getBounds().getWidth(), dateWidth);

        TextLayout planStatus = new TextLayout(
                build.getPlanStateString().length() > 0 ? build.getPlanStateString() : " ", l.getFont(),
                new FontRenderContext(null, true, true));
        planInProgressWidth = Math.max(planStatus.getBounds().getWidth(), planInProgressWidth);
    }
}

From source file:net.fenyo.gnetwatch.GUI.BasicComponent.java

/**
 * Computes new margins./*  ww  w. ja v a  2  s .c  o m*/
 * @param none.
 * @return void.
 */
// AWT thread
// lock survey: sync_update << sync_value_per_vinterval << HERE
//              synchro << sync_tree << sync_update << sync_value_per_vinterval << events << HERE
//              sync_value_per_vinterval << HERE
private void setMargin() {
    /*
    final String left_values_str = "" + (int) (value_per_vinterval *
        (1 + (dimension.height - axis_margin_top - axis_margin_bottom) / pixels_per_vinterval));
    */
    final String left_values_str = "1000M";
    final TextLayout layout = new TextLayout(left_values_str, backing_g.getFont(),
            backing_g.getFontRenderContext());
    final Rectangle2D bounds = layout.getBounds();
    axis_margin_left = (int) bounds.getWidth() + 5 + 10;
}

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

/**
 * Create an image that contains text/*w  ww.ja va2s  . c om*/
 * 
 * @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:net.fenyo.gnetwatch.GUI.BasicComponent.java

/**
 * Paints axis./*from ww  w .  j  a va2s  .  co  m*/
 * @param none.
 * @return long current time displayed at the axis bottom.
 */
// AWT thread
private long paintAxis() {
    backing_g.setColor(new Color(50, 50, 50));
    backing_g.fillRect(axis_margin_left, axis_margin_top,
            dimension.width - axis_margin_left - axis_margin_right + 1,
            dimension.height - axis_margin_top - axis_margin_bottom + 1);

    backing_g.setColor(Color.YELLOW);
    backing_g.drawLine(axis_margin_left, dimension.height - axis_margin_bottom,
            dimension.width - axis_margin_right, dimension.height - axis_margin_bottom);
    backing_g.drawLine(axis_margin_left, axis_margin_top, axis_margin_left,
            dimension.height - axis_margin_bottom);

    backing_g.setColor(Color.YELLOW.darker());
    backing_g.drawLine(axis_margin_left + 1, axis_margin_top, dimension.width - axis_margin_right,
            axis_margin_top);
    backing_g.drawLine(dimension.width - axis_margin_right, axis_margin_top,
            dimension.width - axis_margin_right, dimension.height - axis_margin_bottom - 1);

    int vinterval_pos = dimension.height - axis_margin_bottom - pixels_per_vinterval;
    backing_g.setColor(Color.YELLOW.darker().darker().darker());
    while (vinterval_pos + 9 * (pixels_per_vinterval / 10) > axis_margin_top) {
        int cpt = 10;
        while (--cpt > 0)
            if (vinterval_pos + cpt * (pixels_per_vinterval / 10) > axis_margin_top)
                backing_g.drawLine(axis_margin_left + 1, vinterval_pos + cpt * (pixels_per_vinterval / 10),
                        dimension.width - axis_margin_right - 1,
                        vinterval_pos + cpt * (pixels_per_vinterval / 10));
        vinterval_pos -= pixels_per_vinterval;
    }

    final long now;
    if (manual_mode)
        now = manual_now;
    else
        now = System.currentTimeMillis();

    final long time_to_display = now - now % _getDelayPerInterval();
    final int pixels_offset = (pixels_per_interval * (int) (now % _getDelayPerInterval()))
            / (int) _getDelayPerInterval();
    final int last_interval_pos = dimension.width - axis_margin_right - pixels_offset;

    backing_g.setClip(axis_margin_left, 0, dimension.width - axis_margin_left - axis_margin_right,
            dimension.height);
    int current_interval_pos = last_interval_pos + pixels_per_interval;
    long current_time_to_display = time_to_display + _getDelayPerInterval();
    boolean stop = false;
    while (stop == false) {
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawLine(current_interval_pos, axis_margin_top, current_interval_pos,
                dimension.height - axis_margin_bottom + std_separator);

        int cpt = 10;
        backing_g.setColor(Color.YELLOW.darker().darker().darker());
        while (--cpt > 0)
            if (current_interval_pos - cpt * (pixels_per_interval / 10) > axis_margin_left)
                backing_g.drawLine(current_interval_pos - cpt * (pixels_per_interval / 10), axis_margin_top + 1,
                        current_interval_pos - cpt * (pixels_per_interval / 10),
                        dimension.height - axis_margin_bottom - 1);

        final String current_time_str = formatTime(current_time_to_display);
        final String current_date_str = formatDate(current_time_to_display);
        final TextLayout current_layout = new TextLayout(current_time_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final TextLayout current_layout_date = new TextLayout(current_date_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final Rectangle2D current_bounds = current_layout.getBounds();
        final Rectangle2D current_bounds_date = current_layout_date.getBounds();
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawString(current_time_str, current_interval_pos - (int) (current_bounds.getWidth() / 2),
                dimension.height - axis_margin_bottom + (int) current_bounds.getHeight() + 2 * std_separator);
        backing_g.setColor(Color.YELLOW.darker().darker());
        backing_g.drawString(current_date_str,
                current_interval_pos - (int) (current_bounds_date.getWidth() / 2),
                3 + ((int) current_bounds.getHeight()) + dimension.height - axis_margin_bottom
                        + (int) current_bounds.getHeight() + 2 * std_separator);
        if (current_interval_pos - current_bounds.getWidth() / 2 < axis_margin_left)
            stop = true;
        current_interval_pos -= pixels_per_interval;
        current_time_to_display -= _getDelayPerInterval();
    }
    backing_g.setClip(null);

    vinterval_pos = dimension.height - axis_margin_bottom - pixels_per_vinterval;
    int value = value_per_vinterval;
    while (vinterval_pos > axis_margin_top) {
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawLine(axis_margin_left - std_separator, vinterval_pos, dimension.width - axis_margin_right,
                vinterval_pos);
        final String value_str;
        if (value >= 1000000)
            value_str = "" + value / 1000000 + "M";
        else if (value >= 1000)
            value_str = "" + value / 1000 + "k";
        else
            value_str = "" + value;
        final TextLayout current_layout = new TextLayout(value_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final Rectangle2D current_bounds = current_layout.getBounds();
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawString(value_str, axis_margin_left - (int) current_bounds.getWidth() - 2 * std_separator,
                vinterval_pos + (int) (current_bounds.getHeight() / 2));
        vinterval_pos -= pixels_per_vinterval;
        value += value_per_vinterval;
    }

    return now;
}