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:org.dishevelled.brainstorm.BrainStorm.java

/**
 * Calculate the text area size in rows and columns based on the current
 * window size and text area font size./*ww w. j a  v a2  s  .c o m*/
 */
private void calculateTextAreaSize() {
    double width = (double) getWidth();
    FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
    TextLayout textLayout = new TextLayout("W", textArea.getFont(), frc);
    Rectangle2D textBounds = textLayout.getBounds();
    int columns = Math.min(45, (int) (width / textBounds.getWidth()) - 4);
    textArea.setColumns(columns);
}

From source file:org.earthtime.UPb_Redux.dateInterpretation.WeightedMeanGraphPanel.java

private void drawAxesAndTicks(Graphics2D g2d, double rangeX, double rangeY) {

    // oct 2014 new tic logic
    // reset the clip bounds to paint axis and numbers
    g2d.setClip(0, 0, getWidth(), getHeight());

    g2d.setFont(new Font("Monospaced", Font.BOLD, 14));
    g2d.setPaint(Color.BLACK);/*from w w  w .  j  a  va  2 s .  c  om*/
    g2d.setStroke(new BasicStroke(2.0f));

    // determine the axis ticks
    BigDecimal[] tics = TicGeneratorForAxes.generateTics(getMinY_Display(), getMaxY_Display(), 12);
    // trap for bad plot
    if (tics.length <= 1) {
        tics = new BigDecimal[0];
    }
    double minXDisplay = 0.0;
    int yAxisTicWidth = 8;
    int yTicLabelFrequency = 2;
    int labeledTicCountYAxis = 0;

    g2d.setPaint(Color.black);
    for (int i = 0; i < tics.length; i++) {

        double y = tics[i].doubleValue();

        if ((y > getMinY_Display()) // dont print across mappedX axis
                && (y < getMaxY_Display())) // dont print across top border
        {
            try {
                Shape ticMark = new Line2D.Double( //
                        mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth),
                        mapY(y, getMaxY_Display(), rangeY, graphHeight),
                        mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) + 7,
                        mapY(y, getMaxY_Display(), rangeY, graphHeight));
                g2d.draw(ticMark);

                String intString = "00000" + tics[i].toPlainString().replace(".", "");
                int lastPlace = Integer.parseInt(intString.substring(intString.length() - 4));

                if (lastPlace % yTicLabelFrequency == 0) {
                    if (labeledTicCountYAxis % yTicLabelFrequency == 0) {

                        TextLayout mLayout = //
                                new TextLayout(tics[i].toPlainString(), g2d.getFont(),
                                        g2d.getFontRenderContext());

                        Rectangle2D bounds = mLayout.getBounds();

                        //if (isyAxisHorizontalTicLabels()) {
                        //                            g2d.drawString(tics[i].toPlainString(),//
                        //                                    (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                        //                                    (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
                        //                            } else {
                        float yLabelCenterOffset = (float) mLayout.getBounds().getWidth() / 2f;

                        g2d.rotate(-Math.PI / 2.0,
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                        g2d.drawString(tics[i].toPlainString(),
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                        g2d.rotate(Math.PI / 2.0,
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                    }

                    labeledTicCountYAxis++;
                } else {

                    if (labeledTicCountYAxis > 0) {
                        labeledTicCountYAxis++;
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    ////        // reset the clip bounds to paint axis and numbers
    ////        g2d.setClip(0, 0, getWidth(), getHeight());
    ////
    ////        g2d.setFont(new Font("Monospaced", Font.BOLD, 14));
    ////        g2d.setPaint(Color.BLACK);
    ////        g2d.setStroke(new BasicStroke(2.0f));
    ////
    ////        // determine the axis ticks
    ////        double minYtick = Math.ceil(getMinY_Display() * 100) / 100;
    ////        double maxYtick = Math.floor(getMaxY_Display() * 100) / 100;
    ////
    ////        int count = 0;
    ////        double deltay = Math.rint((maxYtick - minYtick) * 10 + 0.5);
    ////        double stepYtick = deltay / 100;
    ////
    ////        for (double y = minYtick; y
    ////                < maxYtick; y
    ////                += stepYtick) {
    ////            Line2D line = new Line2D.Double(
    ////                    mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth),
    ////                    mapY(y, getMaxY_Display(), rangeY, graphHeight),
    ////                    mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) + 7,
    ////                    mapY(y, getMaxY_Display(), rangeY, graphHeight));
    ////            g2d.draw(line);
    ////
    ////            if ((count % 2) == 1) {
    ////                NumberFormat yFormat = null;
    ////                String temp = null;
    ////
    ////                yFormat
    ////                        = new DecimalFormat("0.00");
    ////                temp
    ////                        = yFormat.format(y);
    ////
    ////                g2d.setPaint(Color.black);
    ////                g2d.rotate(
    ////                        -Math.PI / 2.0,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////                g2d.drawString(
    ////                        temp,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////                g2d.rotate(
    ////                        Math.PI / 2.0,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////
    ////            }
    ////
    ////            count++;
    ////
    ////        }
    // draw and label axes
    g2d.setFont(new Font("Monospaced", Font.BOLD, 20));
    g2d.drawRect(getLeftMargin(), getTopMargin(), getGraphWidth() - 1, getGraphHeight() - 1);

}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) {
    log.debug("paintThumbnail entry " + photo.getUuid());
    long startTime = System.currentTimeMillis();
    long thumbReadyTime = 0;
    long thumbDrawnTime = 0;
    long endTime = 0;
    // Current position in which attributes can be drawn
    int ypos = starty + rowHeight / 2;
    boolean useOldThumbnail = false;

    Thumbnail thumbnail = null;/*  ww w .  j  av  a 2s . c om*/
    log.debug("finding thumb");
    boolean hasThumbnail = photo.hasThumbnail();
    log.debug("asked if has thumb");
    if (hasThumbnail) {
        log.debug("Photo " + photo.getUuid() + " has thumbnail");
        thumbnail = photo.getThumbnail();
        log.debug("got thumbnail");
    } else {
        /*
         Check if the thumbnail has been just invalidated. If so, use the 
         old one until we get the new thumbnail created.
         */
        thumbnail = photo.getOldThumbnail();
        if (thumbnail != null) {
            useOldThumbnail = true;
        } else {
            // No success, use default thumnail.
            thumbnail = Thumbnail.getDefaultThumbnail();
        }

        // Inform background task scheduler that we have some work to do
        ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL);
    }
    thumbReadyTime = System.currentTimeMillis();

    log.debug("starting to draw");
    // Find the position for the thumbnail
    BufferedImage img = thumbnail.getImage();
    if (img == null) {
        thumbnail = Thumbnail.getDefaultThumbnail();
        img = thumbnail.getImage();
    }

    float scaleX = ((float) thumbWidth) / ((float) img.getWidth());
    float scaleY = ((float) thumbHeight) / ((float) img.getHeight());
    float scale = Math.min(scaleX, scaleY);
    int w = (int) (img.getWidth() * scale);
    int h = (int) (img.getHeight() * scale);

    int x = startx + (columnWidth - w) / (int) 2;
    int y = starty + (rowHeight - h) / (int) 2;

    log.debug("drawing thumbnail");

    // Draw shadow
    int offset = isSelected ? 2 : 0;
    int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset };
    int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset };
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length);
    polyline.moveTo(shadowX[0], shadowY[0]);
    for (int index = 1; index < shadowX.length; index++) {
        polyline.lineTo(shadowX[index], shadowY[index]);
    }
    ;
    BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    Stroke oldStroke = g2.getStroke();
    g2.setStroke(shadowStroke);
    g2.setColor(Color.DARK_GRAY);
    g2.draw(polyline);
    g2.setStroke(oldStroke);

    // Paint thumbnail
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null);
    if (useOldThumbnail) {
        creatingThumbIcon.paintIcon(this, g2,
                startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2,
                starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2);
    }
    log.debug("Drawn, drawing decorations");
    if (isSelected) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(3.0f));
        g2.setColor(Color.BLUE);
        g2.drawRect(x, y, w, h);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
    }

    thumbDrawnTime = System.currentTimeMillis();

    boolean drawAttrs = (thumbWidth >= 100);
    if (drawAttrs) {
        // Increase ypos so that attributes are drawn under the image
        ypos += ((int) h) / 2 + 3;

        // Draw the attributes

        // Draw the qualoity icon to the upper left corner of the thumbnail
        int quality = photo.getQuality();
        if (showQuality && quality != 0) {
            int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2;
            for (int n = 0; n < quality; n++) {
                starIcon.paintIcon(this, g2, qx, ypos);
                qx += starIcon.getIconWidth();
            }
            ypos += starIcon.getIconHeight();
        }
        ypos += 6;

        if (photo.getRawSettings() != null) {
            // Draw the "RAW" icon
            int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5;
            int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5;
            rawIcon.paintIcon(this, g2, rx, ry);
        }
        if (photo.getHistory().getHeads().size() > 1) {
            // Draw the "unresolved conflicts" icon
            int rx = startx + (columnWidth + w - 10) / (int) 2 - 20;
            int ry = starty + (columnWidth - h - 10) / (int) 2;
            g2.setColor(Color.RED);
            g2.fillRect(rx, ry, 10, 10);
        }

        Color prevBkg = g2.getBackground();
        if (isSelected) {
            g2.setBackground(Color.BLUE);
        } else {
            g2.setBackground(this.getBackground());
        }
        Font attrFont = new Font("Arial", Font.PLAIN, 10);
        FontRenderContext frc = g2.getFontRenderContext();
        if (showDate && photo.getShootTime() != null) {
            FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy());

            String dateStr = fd.format();
            TextLayout txt = new TextLayout(dateStr, attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();
            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        String shootPlace = photo.getShootingPlace();
        if (showPlace && shootPlace != null && shootPlace.length() > 0) {
            TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();

            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        g2.setBackground(prevBkg);
    }
    endTime = System.currentTimeMillis();
    log.debug("paintThumbnail: exit " + photo.getUuid());
    log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms");
    log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms");
    log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms");
    log.debug("Total " + (endTime - startTime) + " ms");
}

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

/**
 * Compute width of a single cell//ww w  . j a v  a  2  s  .c o  m
 *
 * @param cell the cell whose width is to be calculated
 * @param defaultCharWidth the width of a single character
 * @param formatter formatter used to prepare the text to be measured
 * @param useMergedCells    whether to use merged cells
 * @return  the width in pixels
 */
public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter,
        boolean useMergedCells) {

    Sheet sheet = cell.getSheet();
    Workbook wb = sheet.getWorkbook();
    Row row = cell.getRow();
    int column = cell.getColumnIndex();

    int colspan = 1;
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        CellRangeAddress region = sheet.getMergedRegion(i);
        if (containsCell(region, row.getRowNum(), column)) {
            if (!useMergedCells) {
                // If we're not using merged cells, skip this one and move on to the next.
                return -1;
            }
            cell = row.getCell(region.getFirstColumn());
            colspan = 1 + region.getLastColumn() - region.getFirstColumn();
        }
    }

    CellStyle style = cell.getCellStyle();
    int cellType = cell.getCellType();

    // for formula cells we compute the cell width for the cached formula result
    if (cellType == Cell.CELL_TYPE_FORMULA)
        cellType = cell.getCachedFormulaResultType();

    Font font = wb.getFontAt(style.getFontIndex());

    AttributedString str;
    TextLayout layout;

    double width = -1;
    if (cellType == Cell.CELL_TYPE_STRING) {
        RichTextString rt = cell.getRichStringCellValue();
        String[] lines = rt.getString().split("\\n");
        for (int i = 0; i < lines.length; i++) {
            String txt = lines[i] + defaultChar;

            str = new AttributedString(txt);
            copyAttributes(font, str, 0, txt.length());

            if (rt.numFormattingRuns() > 0) {
                // TODO: support rich text fragments
            }

            layout = new TextLayout(str.getIterator(), fontRenderContext);
            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));
                width = Math.max(width,
                        ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                                + cell.getCellStyle().getIndention());
            } else {
                width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                        + cell.getCellStyle().getIndention());
            }
        }
    } else {
        String sval = null;
        if (cellType == Cell.CELL_TYPE_NUMERIC) {
            // Try to get it formatted to look the same as excel
            try {
                sval = formatter.formatCellValue(cell, dummyEvaluator);
            } catch (Exception e) {
                sval = String.valueOf(cell.getNumericCellValue());
            }
        } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
            sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase();
        }
        if (sval != null) {
            String txt = sval + defaultChar;
            str = new AttributedString(txt);
            copyAttributes(font, str, 0, txt.length());

            layout = new TextLayout(str.getIterator(), fontRenderContext);
            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));
                width = Math.max(width,
                        ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                                + cell.getCellStyle().getIndention());
            } else {
                width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                        + cell.getCellStyle().getIndention());
            }
        }
    }
    return width;
}

From source file:ru.runa.wfe.graph.image.figure.AbstractFigure.java

private int drawText(Graphics2D graphics, String text, int hOffset) {
    Rectangle r = getTextBoundsRectangle();
    Rectangle2D textBounds = graphics.getFontMetrics().getStringBounds(text, graphics);
    if (textBounds.getWidth() > r.getWidth() - 4) {
        int y = coords[1] + hOffset;
        AttributedString attributedString = new AttributedString(text);
        attributedString.addAttribute(TextAttribute.FONT, graphics.getFont());
        AttributedCharacterIterator characterIterator = attributedString.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, graphics.getFontRenderContext());
        while (measurer.getPosition() < characterIterator.getEndIndex()) {
            TextLayout textLayout = measurer.nextLayout((float) r.getWidth() - 4);
            y += textLayout.getAscent();
            float x = (float) (r.getCenterX() + 2 - textLayout.getBounds().getCenterX());
            textLayout.draw(graphics, x, y);
            y += textLayout.getDescent() + textLayout.getLeading();
        }//from  w  w w .  j ava  2s . com
        return y - coords[1];
    } else {
        graphics.drawString(text, (float) (r.getCenterX() + 2 - textBounds.getCenterX()),
                (float) (coords[1] + textBounds.getHeight() + hOffset));
        return (int) (textBounds.getHeight() + hOffset + 3);
    }
}