Java Code Examples for java.awt.font.TextLayout#getBounds()

The following examples show how to use java.awt.font.TextLayout#getBounds() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ET_Redux   File: XAxisOverlayViewLabel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param g2d
 */
@Override
public void paint ( Graphics2D g2d ) {
    paintInit( g2d );

    String label = "Elapsed Seconds:";
    TextLayout mLayout = //
            new TextLayout(
            label, g2d.getFont(), g2d.getFontRenderContext() );

    Rectangle2D bounds = mLayout.getBounds();

    g2d.drawString( label,//
            getWidth() - (float) (bounds.getWidth()) - 2f,//
            (float) mapY( getRangeY_Display() / 2.0 ) + (float)(bounds.getHeight() / 2f) );

}
 
Example 2
Source Project: depan   File: FontManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Render the given text directly to a texture using java2D, and return this
 * texture. The text is painted in white, using transparency. One can then
 * redefine the color just before rendering, with a glColor call.
 *
 * @param text text to paint.
 * @return
 */
public static TextureRenderer makeText(String text) {
  // create texture for the text
  TextureRenderer textRenderer = new TextureRenderer(1, 3, false);
  Graphics2D g2d = textRenderer.createGraphics();
  FontRenderContext frc = g2d.getFontRenderContext();
  Font f = new Font("Arial", Font.BOLD, 18);
  String s = new String(text);
  TextLayout tl = new TextLayout(s, f, frc);
  // get the necessary size for the text to be rendered
  Rectangle2D bounds = tl.getBounds();
  // add some margin...
  int width = (int) bounds.getWidth() + 6;
  int height = (int) bounds.getHeight() + 6;
  // create a new texture renderer with the exact correct width and height.
  textRenderer = new TextureRenderer(width, height, true);
  textRenderer.setSmoothing(true);
  g2d = textRenderer.createGraphics();
  g2d.setColor(Color.white);
  //coordinate are inversed: 0:0 is top-left.
  tl.draw(g2d, 3, height - 3);

  textRenderer.markDirty(0, 0, width, height);
  return textRenderer;
}
 
Example 3
Source Project: ET_Redux   File: ResidualsYAxisLabel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param g2d
 */
@Override
public void paint ( Graphics2D g2d ) {
    paintInit( g2d );

    g2d.setStroke( new BasicStroke( 1.0f ) );
    g2d.drawLine( 0, 0, getWidth() - 1, 0 );

    String label = "Residuals:";
    TextLayout mLayout = //
            new TextLayout(
            label, g2d.getFont(), g2d.getFontRenderContext() );

    Rectangle2D bounds = mLayout.getBounds();

    g2d.drawString( label,//
            getWidth() - (float) (bounds.getWidth()) - 2f,//
            (float) mapY( getRangeY_Display() / 2.0 ) + (float) (bounds.getHeight() / 2f) );

}
 
Example 4
/**
 * This is the general paint method for drawing a symbol layout, at
 * a specified location, using a specified alignment.
 *
 * @param g         the graphics environment
 * @param layout    what: the symbol, perhaps transformed
 * @param location  where: the precise location in the display
 * @param alignment how: the way the symbol is aligned wrt the location
 */
public static void paint (Graphics2D g,
                          TextLayout layout,
                          Point location,
                          Alignment alignment)
{
    try {
        // Compute symbol origin
        Rectangle2D bounds = layout.getBounds();
        Point2D toTextOrigin = alignment.toTextOrigin(bounds);
        Point2D origin = new Point2D.Double(
                location.x + toTextOrigin.getX(),
                location.y + toTextOrigin.getY());

        // Draw the symbol
        layout.draw(g, (float) origin.getX(), (float) origin.getY());
    } catch (ConcurrentModificationException ignored) {
    } catch (Exception ex) {
        logger.warn("Cannot paint at " + location, ex);
    }
}
 
Example 5
Source Project: lams   File: SheetUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculate the best-fit width for a cell
 * If a merged cell spans multiple columns, evenly distribute the column width among those columns
 *
 * @param defaultCharWidth the width of a character using the default font in a workbook
 * @param colspan the number of columns that is spanned by the cell (1 if the cell is not part of a merged region)
 * @param style the cell style, which contains text rotation and indention information needed to compute the cell width
 * @param minWidth the minimum best-fit width. This algorithm will only return values greater than or equal to the minimum width.
 * @param str the text contained in the cell
 * @return the best fit cell width
 */
private static double getCellWidth(int defaultCharWidth, int colspan,
        CellStyle style, double minWidth, AttributedString str) {
    TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext);
    final Rectangle2D bounds;
    if(style.getRotation() != 0){
        /*
         * Transform the text using a scale so that it's height is increased by a multiple of the leading,
         * and then rotate the text before computing the bounds. The scale results in some whitespace around
         * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
         * is added by the standard Excel autosize.
         */
        AffineTransform trans = new AffineTransform();
        trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
        trans.concatenate(
        AffineTransform.getScaleInstance(1, fontHeightMultiple)
        );
        bounds = layout.getOutline(trans).getBounds();
    } else {
        bounds = layout.getBounds();
    }
    // frameWidth accounts for leading spaces which is excluded from bounds.getWidth()
    final double frameWidth = bounds.getX() + bounds.getWidth();
    return Math.max(minWidth, ((frameWidth / colspan) / defaultCharWidth) + style.getIndention());
}
 
Example 6
/**
 * Draws the attributed string at {@code (textX, textY)}, rotated by 
 * the specified angle about {@code (rotateX, rotateY)}.
 * 
 * @param text  the attributed string ({@code null} not permitted).
 * @param g2  the graphics output target ({@code null} not permitted).
 * @param textX  the x-coordinate for the text alignment point.
 * @param textY  the y-coordinate for the text alignment point.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @return The text bounds (never {@code null}).
 * 
 * @since 1.2
 */
public static Shape drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    
    Args.nullNotPermitted(text, "text");
    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    Rectangle2D rect = tl.getBounds();
    tl.draw(g2, textX, textY);
    g2.setTransform(saved);
    return rotate.createTransformedShape(rect);
}
 
Example 7
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    Rectangle2D r;
    do {
        r = tl.getBounds();
    } while (--numReps >= 0);
}
 
Example 8
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (convolvedImage != null) {
        int width = getWidth();
        int height = getHeight();

        synchronized (convolvedImage) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

            FontRenderContext context = g2.getFontRenderContext();
            TextLayout layout = new TextLayout(message, font, context);
            Rectangle2D bounds = layout.getBounds();

            int x = (width - convolvedImage.getWidth(null)) / 2;
            int y = (int) (height - (convolvedImage.getHeight(null) + bounds.getHeight() + layout.getAscent())) / 2;

            g2.drawImage(convolvedImage, x, y, this);
            g2.setColor(new Color(0, 0, 0, (int) (gradient * 255)));
            layout.draw(g2, (float) (width - bounds.getWidth()) / 2,
                    (float) (y + convolvedImage.getHeight(null) + bounds.getHeight() + layout.getAscent()));
        }
    }
}
 
Example 9
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    Rectangle2D r;
    do {
        r = tl.getBounds();
    } while (--numReps >= 0);
}
 
Example 10
@Override
public Shape getUnclippedOutline() {
	TextLayout layout = new TextLayout(getAttributedCharacterIterator(),
			getContext().getFontRenderContext());
	Rectangle2D bounds = layout.getBounds();
	bounds.setFrame(bounds.getX() + getX(), bounds.getY() + getY(),
			bounds.getWidth(), bounds.getHeight());
	return bounds;
}
 
Example 11
Source Project: SIMVA-SoS   File: AttrStringUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * A utility method that calculates the rotation anchor offsets for a
 * string.  These offsets are relative to the text starting coordinate
 * (BASELINE_LEFT).
 *
 * @param g2  the graphics device.
 * @param text  the text.
 * @param anchor  the anchor point.
 *
 * @return  The offsets.
 */
private static float[] deriveRotationAnchorOffsets(Graphics2D g2, 
        AttributedString text, TextAnchor anchor) {

    float[] result = new float[2];
    
    TextLayout layout = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    Rectangle2D bounds = layout.getBounds();
    float ascent = layout.getAscent();
    float halfAscent = ascent / 2.0f;
    float descent = layout.getDescent();
    float leading = layout.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (isHorizontalLeft(anchor)) {
        xAdj = 0.0f;
    }
    else if (isHorizontalCenter(anchor)) {
        xAdj = (float) bounds.getWidth() / 2.0f;
    }
    else if (isHorizontalRight(anchor)) {
        xAdj = (float) bounds.getWidth();
    }

    if (isTop(anchor)) {
        yAdj = descent + leading - (float) bounds.getHeight();
    }
    else if (isHalfHeight(anchor)) {
        yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
    }
    else if (isHalfAscent(anchor)) {
        yAdj = -halfAscent;
    }
    else if (isBaseline(anchor)) {
        yAdj = 0.0f;
    }
    else if (isBottom(anchor)) {
        yAdj = descent + leading;
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}
 
Example 12
/**
 * A utility method that calculates the rotation anchor offsets for a
 * string.  These offsets are relative to the text starting coordinate
 * (BASELINE_LEFT).
 *
 * @param g2  the graphics device.
 * @param text  the text.
 * @param anchor  the anchor point.
 *
 * @return  The offsets.
 */
private static float[] deriveRotationAnchorOffsets(Graphics2D g2, 
        AttributedString text, TextAnchor anchor) {

    float[] result = new float[2];
    
    TextLayout layout = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    Rectangle2D bounds = layout.getBounds();
    float ascent = layout.getAscent();
    float halfAscent = ascent / 2.0f;
    float descent = layout.getDescent();
    float leading = layout.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (isHorizontalLeft(anchor)) {
        xAdj = 0.0f;
    }
    else if (isHorizontalCenter(anchor)) {
        xAdj = (float) bounds.getWidth() / 2.0f;
    }
    else if (isHorizontalRight(anchor)) {
        xAdj = (float) bounds.getWidth();
    }

    if (isTop(anchor)) {
        yAdj = descent + leading - (float) bounds.getHeight();
    }
    else if (isHalfHeight(anchor)) {
        yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
    }
    else if (isHalfAscent(anchor)) {
        yAdj = -halfAscent;
    }
    else if (isBaseline(anchor)) {
        yAdj = 0.0f;
    }
    else if (isBottom(anchor)) {
        yAdj = descent + leading;
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}
 
Example 13
private void drawTics(Graphics2D g2d) {
        // plot grid
        g2d.setColor(Color.darkGray);
        g2d.setStroke(new BasicStroke(1.0f));
        g2d.drawRect(
                leftMargin, getTopMargin(), (int) getGraphWidth() - 1, (int) getGraphHeight() - 1);

//        g2d.setClip( 0/*getLeftMargin()*/, getTopMargin(), getGraphWidth(), getGraphHeight() + 15 );
        DecimalFormat dateFormat = new DecimalFormat("###0");
        g2d.setStroke(new BasicStroke(0.5f));

        // round to the highest N00000...
        double ticFreq = ((maxX - minX) / 10);
        double digits = Math.ceil(Math.log10(ticFreq)) - 1;
        double tenPow = Math.pow(10, digits);
        ticFreq = Math.floor(ticFreq / tenPow) * tenPow;

        for (int i = 0; i < 4001; i += ticFreq) {

            if (mapX(i) > leftMargin) {
                Line2D tic = new Line2D.Double(
                        mapX(i),
                        mapY(getMinY_Display()) + 5,
                        mapX(i),
                        mapY(getMinY_Display() + maxY));
                g2d.draw(tic);

                String temp = dateFormat.format(i);

                // draw number value, adjusting for font
                // build the box to fit the value string
                TextLayout tempLayout
                        = //
                        new TextLayout(
                                temp.trim(), g2d.getFont(), g2d.getFontRenderContext());

                Rectangle2D bounds = tempLayout.getBounds();

                float textX = (float) mapX(i) //
                        - (float) bounds.getWidth() / 2;
                float textY = (float) mapY(getMinY_Display()) + 8 //
                        + (float) bounds.getHeight() * 0.4f;

                g2d.setPaint(Color.black);
                g2d.drawString(temp, textX, textY);
            }
        }
    }
 
Example 14
@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    
    ButtonModel m = getModel();
    Insets insets = getInsets();
    
    int width = getWidth() - insets.left - insets.right;
    int height = getHeight() - insets.top - insets.bottom;
    
    tileStretchPaint(g2,this,(BufferedImage) getImage(m.isArmed()), sourceInsets);
    
    if (getModel().isRollover()) {
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(buttonHighlight,
                insets.left + 2, insets.top + 2,
                width - 4, height - 4, null);
    }
    
    FontMetrics fm = getFontMetrics(getFont());
    TextLayout layout = new TextLayout(getText(),
            getFont(),
            g2.getFontRenderContext());
    Rectangle2D bounds = layout.getBounds();
    
    int x = (int) (getWidth() - insets.left - insets.right -
            bounds.getWidth()) / 2;
    //x -= 2;
    int y = (getHeight() - insets.top - insets.bottom -
             fm.getMaxAscent() - fm.getMaxDescent()) / 2;
    y += fm.getAscent() - 1;
    
    if (m.isArmed()) {
        x += 1;
        y += 1;
    }
    
    g2.setColor(shadowColor);
    layout.draw(g2,
            x + (int) Math.ceil(shadowOffsetX),
            y + (int) Math.ceil(shadowOffsetY));
    g2.setColor(getForeground());
    layout.draw(g2, x, y);
}
 
Example 15
Source Project: freecol   File: Canvas.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void paintComponent(Graphics g) {
    Dimension size = checkResize();
    boolean hasMap = this.freeColClient != null
        && this.freeColClient.getGame() != null
        && this.freeColClient.getGame().getMap() != null;
    Graphics2D g2d = (Graphics2D) g;

    if (freeColClient.isMapEditor()) {
        if (hasMap) {
            mapViewer.displayMap(g2d);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }

    } else if (freeColClient.isInGame() && hasMap) {
        // draw the map
        mapViewer.displayMap(g2d);

        // toggle grey layer if needed
        if (freeColClient.currentPlayerIsMyPlayer()) {
            if (greyLayer.getParent() != null) {
                removeFromCanvas(greyLayer);
            }
        } else {
            greyLayer.setBounds(0, 0, size.width, size.height);
            greyLayer.setPlayer(freeColClient.getGame().getCurrentPlayer());
            if (greyLayer.getParent() == null) {
                addToCanvas(greyLayer, JLayeredPane.DRAG_LAYER);
            }
        }

        // draw the chat
        this.chatDisplay.display(g2d, this.imageLibrary, size);

    } else { /* main menu */
        // Get the background without scaling, to avoid wasting
        // memory needlessly keeping an unbounded number of rescaled
        // versions of the largest image in FreeCol, forever.
        final Image bgImage = ImageLibrary.getCanvasBackgroundImage();
        if (bgImage != null) {
            // Draw background image with scaling.
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(bgImage, 0, 0, size.width, size.height, this);
            String versionStr = "v. " + FreeCol.getVersion();
            Font oldFont = g2d.getFont();
            Color oldColor = g2d.getColor();
            Font newFont = oldFont.deriveFont(Font.BOLD);
            TextLayout layout = new TextLayout(versionStr, newFont,
                g2d.getFontRenderContext());
            Rectangle2D bounds = layout.getBounds();
            float x = size.width - (float) bounds.getWidth() - 5;
            float y = size.height - (float) bounds.getHeight();
            g2d.setColor(Color.white);
            layout.draw(g2d, x, y);
            g2d.setFont(oldFont);
            g2d.setColor(oldColor);
        } else {
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, size.width, size.height);
            logger.warning("Unable to load the canvas background");
        }
    }
}
 
Example 16
@Override
protected MyParams getParams (MusicFont font)
{
    MyParams p = new MyParams();

    p.layouts = new SmartLayout[codes.length];

    // Union of all rectangles
    Rectangle2D rect = null;

    // Current abscissa
    float x = 0;

    for (int i = 0; i < codes.length; i++) {
        int code = codes[i];
        TextLayout layout = font.layout(code);
        Rectangle2D r = layout.getBounds();

        // Abscissa reduction because of slanted characters
        // It's value depends on whether we have a 'f' or not
        float dx;
        int c = code - MusicFont.CODE_OFFSET;

        if ((c == 102) || // F
                (c == 196) || // FF
                (c == 236) || // FFF
                (c == 83) || // SF
                (c == 90)) { // FZ
            dx = (float) r.getHeight() * 0.215f; // Measured
        } else {
            dx = (float) r.getHeight() * 0.075f; // Measured
        }

        p.layouts[i] = new SmartLayout(layout, dx);

        if (i > 0) {
            x -= dx;
        }

        if (i == 0) {
            rect = layout.getPixelBounds(null, x, 0);
        } else {
            Rectangle2D.union(
                    rect,
                    layout.getPixelBounds(null, x, 0),
                    rect);
        }

        x += (r.getWidth() - dx);
    }

    p.rect = new Rectangle(
            (int) Math.floor(rect.getX()),
            (int) Math.floor(rect.getY()),
            (int) Math.ceil(rect.getWidth()),
            (int) Math.ceil(rect.getHeight()));

    return p;
}
 
Example 17
/**
 * A utility method that calculates the rotation anchor offsets for a
 * string.  These offsets are relative to the text starting coordinate
 * (BASELINE_LEFT).
 *
 * @param g2  the graphics device.
 * @param text  the text.
 * @param anchor  the anchor point.
 *
 * @return  The offsets.
 */
private static float[] deriveRotationAnchorOffsets(Graphics2D g2, 
        AttributedString text, TextAnchor anchor) {

    float[] result = new float[2];
    
    TextLayout layout = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    Rectangle2D bounds = layout.getBounds();
    float ascent = layout.getAscent();
    float halfAscent = ascent / 2.0f;
    float descent = layout.getDescent();
    float leading = layout.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (isHorizontalLeft(anchor)) {
        xAdj = 0.0f;
    }
    else if (isHorizontalCenter(anchor)) {
        xAdj = (float) bounds.getWidth() / 2.0f;
    }
    else if (isHorizontalRight(anchor)) {
        xAdj = (float) bounds.getWidth();
    }

    if (isTop(anchor)) {
        yAdj = descent + leading - (float) bounds.getHeight();
    }
    else if (isHalfHeight(anchor)) {
        yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
    }
    else if (isHalfAscent(anchor)) {
        yAdj = -halfAscent;
    }
    else if (isBaseline(anchor)) {
        yAdj = 0.0f;
    }
    else if (isBottom(anchor)) {
        yAdj = descent + leading;
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}
 
Example 18
/**
 * Returns the bounds for the attributed string.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics target (<code>null</code> not permitted).
 * 
 * @return The bounds (never <code>null</code>).
 * 
 * @since 1.0.18
 */
public static Rectangle2D getTextBounds(AttributedString text, 
        Graphics2D g2) {
    TextLayout tl = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    return tl.getBounds();
}
 
Example 19
/**
 * Returns the bounds for the attributed string.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics target (<code>null</code> not permitted).
 * 
 * @return The bounds (never <code>null</code>).
 * 
 * @since 1.0.18
 */
public static Rectangle2D getTextBounds(AttributedString text, 
        Graphics2D g2) {
    TextLayout tl = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    return tl.getBounds();
}
 
Example 20
private void drawAvatarText(Graphics2D g2, double y, double bulletHeight) {
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("Dialog", Font.PLAIN, 18);
        TextLayout layout = new TextLayout(textAvatar, font, context);
        Rectangle2D bounds = layout.getBounds();

        float text_x = (float) ((getWidth() - bounds.getWidth()) / 2.0);
        float text_y = (float) (y + (bulletHeight - layout.getAscent() - 
                                     layout.getDescent()) / 2.0) +
                                     layout.getAscent() - layout.getLeading();

        g2.setColor(Color.BLACK);
        layout.draw(g2, text_x, text_y + 1);
        g2.setColor(Color.WHITE);
        layout.draw(g2, text_x, text_y);
    }