Example usage for java.text AttributedString getIterator

List of usage examples for java.text AttributedString getIterator

Introduction

In this page you can find the example usage for java.text AttributedString getIterator.

Prototype

public AttributedCharacterIterator getIterator() 

Source Link

Document

Creates an AttributedCharacterIterator instance that provides access to the entire contents of this string.

Usage

From source file:lucee.runtime.img.Image.java

public void drawString(String text, int x, int y, Struct attr) throws PageException {

    if (attr != null && attr.size() > 0) {

        // font//from   w  w w  .ja  v  a 2s  .c o m
        String font = StringUtil.toLowerCase(Caster.toString(attr.get("font", ""))).trim();
        if (!StringUtil.isEmpty(font)) {
            font = FontUtil.getFont(font).getFontName();
        } else
            font = "Serif";

        // alpha
        //float alpha=Caster.toFloatValue(attr.get("alpha",null),1F);

        // size
        int size = Caster.toIntValue(attr.get("size", Constants.INTEGER_10));

        // style
        int style = Font.PLAIN;
        String strStyle = StringUtil.toLowerCase(Caster.toString(attr.get("style", "")));
        strStyle = StringUtil.removeWhiteSpace(strStyle);
        if (!StringUtil.isEmpty(strStyle)) {
            if ("plain".equals(strStyle))
                style = Font.PLAIN;
            else if ("bold".equals(strStyle))
                style = Font.BOLD;
            else if ("italic".equals(strStyle))
                style = Font.ITALIC;
            else if ("bolditalic".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("bold,italic".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("italicbold".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("italic,bold".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else
                throw new ExpressionException("key style of argument attributeCollection has an invalid value ["
                        + strStyle + "], valid values are [plain,bold,italic,bolditalic]");
        }

        // strikethrough
        boolean strikethrough = Caster.toBooleanValue(attr.get("strikethrough", Boolean.FALSE));

        // underline
        boolean underline = Caster.toBooleanValue(attr.get("underline", Boolean.FALSE));

        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FONT, new Font(font, style, size));
        if (strikethrough)
            as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        if (underline)
            as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        Graphics2D g = getGraphics();
        //if(alpha!=1D) setAlpha(g,alpha);

        g.drawString(as.getIterator(), x, y);
    } else
        getGraphics().drawString(text, x, y);

}

From source file:org.gitools.ui.app.heatmap.drawer.AbstractHeatmapDrawer.java

protected static void paintCell(Decoration decoration, Color gridColor, int gridSize, int offsetX, int offsetY,
        int width, int height, Graphics2D g, Rectangle box) {

    int y = box.y + offsetY;
    int x = box.x + offsetX;

    g.setColor(decoration.getBgColor());
    g.fillRect(x, y, width, height);/*from w w  w .  j ava 2s.  c  o m*/

    g.setColor(gridColor);
    g.fillRect(x, y + height, width, gridSize);

    String text = decoration.getFormatedValue();
    if (!StringUtils.isEmpty(text)) {

        Font font = g.getFont();

        boolean isRotated = decoration.isRotate();

        int fontHeight = (int) font.getSize2D();

        if (fontHeight <= (isRotated ? width : height)) {

            int textWidth = (int) g.getFontMetrics().getStringBounds(text, g).getWidth();
            //TODO: textWidth depends on SuperScript

            if (textWidth < (isRotated ? height : width)) {

                int leftMargin = ((width - textWidth) / 2) + 1;
                int bottomMargin = ((height - fontHeight) / 2) + 1;

                if (isRotated) {
                    leftMargin = ((width - fontHeight) / 2) + 1;
                    bottomMargin = height - (((height - textWidth) / 2));
                }

                g.setColor(Colors.bestForegroundColor(decoration.getBgColor()));
                if (text.matches("[0-9\\.]+e-?[0-9]+")) {
                    int e_pos = text.indexOf("e") + 3;
                    text = text.replaceAll("e(-?[0-9]+)", "10$1");
                    int superscriptEnd = text.length();
                    AttributedString attText = new AttributedString(text);
                    attText.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, e_pos,
                            superscriptEnd);
                    if (isRotated) {
                        g.rotate(radianAngle90);
                        g.drawString(attText.getIterator(), y + height - bottomMargin, -x - leftMargin - 1);
                        g.rotate(-radianAngle90);
                    } else {
                        g.drawString(attText.getIterator(), x + leftMargin, y + height - bottomMargin);
                    }
                } else {

                    if (isRotated) {
                        g.rotate(radianAngle90);
                        g.drawString(text, y + height - bottomMargin, -x - leftMargin - 1);

                        if ("CoCA-08".equals(text)) {
                            System.out.println("x = " + x + " leftMargin = " + leftMargin + " width = " + width
                                    + " fontHeight = " + fontHeight);
                        }

                        g.rotate(-radianAngle90);
                    } else {
                        g.drawString(text, x + leftMargin, y + height - bottomMargin);
                    }
                }
            }
        }
    }

}

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

/**
 * Compute width of a single cell//from   w w  w  . j ava 2s. c om
 *
 * @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:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a column and return the result
 *
 * @param sheet the sheet to calculate//from  ww  w.j a  v a 2 s.com
 * @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//  w  ww . ja  v 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;
}

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 ww w .ja  v  a  2  s .c o m*/
        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);
    }
}