Package java.awt.font

Examples of java.awt.font.TextLayout


                               final StyleSheet layoutContext)
  {
    RichTextSpec richText = RichTextSpecProducer.compute(lineBoxContainer, metaData, resourceManager);

    final FontRenderContext fontRenderContext = createFontRenderContext(layoutContext);
    final TextLayout textLayout = new TextLayout(richText.createAttributedCharacterIterator(), fontRenderContext);
    double height = textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading();

    final RenderableComplexText text = richText.create(lineBoxContainer);
    text.setTextLayout(textLayout);
    ParagraphFontMetricsImpl metrics = new ParagraphFontMetricsImpl();
    metrics.update(textLayout);
View Full Code Here


                                 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);
View Full Code Here

  protected TextLayout postProcess(final int start,
                                   final TextLayout textLayout,
                                   final LineBreakMeasurer lineBreakMeasurer)
  {
    int end = lineBreakMeasurer.getPosition();
    final TextLayout layout = performWordBreak(start, textLayout, lineBreakMeasurer, end);
    return super.postProcess(start, layout, lineBreakMeasurer);
  }
View Full Code Here

  private TextLayout performWordBreak(final int start,
                                      final TextLayout textLayout,
                                      final LineBreakMeasurer lineBreakMeasurer, final int end)
  {
    final TextLayout layout;
    if (wordInstance.isBoundary(end) != false)
    {
      return textLayout;
    }
View Full Code Here

  {
    // For each line produced by the LinebreakMeasurer
    int start = lineBreakMeasurer.getPosition();
    // float is the worst option to have accurate layouts. So we have to 'adjust' for rounding errors
    // and hope that no one notices ..
    TextLayout textLayout = lineBreakMeasurer.nextLayout(wrappingWidth + 0.5f, ci.getEndIndex(), false);
    textLayout = postProcess(start, textLayout, lineBreakMeasurer);
    int end = lineBreakMeasurer.getPosition();

    // check if the text must be justified
View Full Code Here

      // This text is empty.
      return;
    }

    final String text;
    TextLayout textLayout = renderableComplexText.getTextLayout();
    String debugInfo = textLayout.toString();
    String startPos = debugInfo.substring(debugInfo.indexOf("[start:"), debugInfo.indexOf(", len:")).replace("[start:", "");
    int startPosIntValue = -1;

    try
    {
      startPosIntValue = Integer.parseInt(startPos);
    }
    catch (NumberFormatException e)
    {
      // do nothing
    }

    // workaround for line breaking (since the text cannot be extracted directly from textLayout as stream or String)
    // in order to avoid duplicates of same source raw text on multiple lines
    if ((renderableComplexText.getRawText().length() > textLayout.getCharacterCount()) && startPosIntValue >= 0)
    {
      text = renderableComplexText.getRawText().substring(startPosIntValue, textLayout.getCharacterCount() + startPosIntValue);
    }
    else
    {
      text = renderableComplexText.getRawText();
    }
View Full Code Here

    for (int end = wordInstance.next(); end != BreakIterator.DONE; start = end, end = wordInstance.next())
    {
      String word = text.substring(start, end);
      AttributedCharacterIterator attributedCharacterIterator =
          new RichTextSpecProducer(data, resourceManager).computeText(this, word).createAttributedCharacterIterator();
      TextLayout t = new TextLayout(attributedCharacterIterator, fontRenderContext);
      double width = t.getVisibleAdvance();
      final long wordMinChunkWidth = StrictGeomUtility.toInternalValue(width);
      minimumChunkWidth = Math.max(minimumChunkWidth, wordMinChunkWidth);
    }

    setMinimumChunkWidth(minimumChunkWidth);
View Full Code Here

    Graphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img);
    FontRenderContext fontRenderContext = graphics.getFontRenderContext();
    this.font = new Font(fontName, Font.PLAIN, 1000);
    double maxHeight = 0;
    for (int i = 0; i < 255; i++) {
      TextLayout layout = new TextLayout(Character.toString((char)i), font, fontRenderContext);
      maxHeight = Math.max(maxHeight, layout.getBounds().getHeight());
      super.widths[i] = (int)layout.getAdvance();
    }

    super.maxCharHeight = (int)Math.round(maxHeight);
  }
View Full Code Here

     * @param column the column index
     * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
     */
    public void autoSizeColumn(int column, boolean useMergedCells) {
        AttributedString str;
        TextLayout layout;
        /**
         * Excel measures columns in units of 1/256th of a character width
         * but the docs say nothing about what particular character is used.
         * '0' looks to be a good choice.
         */
        char defaultChar = '0';

        /**
         * This is the multiple that the font height is scaled by when determining the
         * boundary of rotated text.
         */
        double fontHeightMultiple = 2.0;

        FontRenderContext frc = new FontRenderContext(null, true, true);

        HSSFWorkbook wb = new HSSFWorkbook(_book);
        HSSFFont defaultFont = wb.getFontAt((short) 0);

        str = new AttributedString("" + defaultChar);
        copyAttributes(defaultFont, str, 0, 1);
        layout = new TextLayout(str.getIterator(), frc);
        int defaultCharWidth = (int)layout.getAdvance();

        double width = -1;
        rows:
        for (Iterator<Row> it = rowIterator(); it.hasNext();) {
            HSSFRow row = (HSSFRow) it.next();
            HSSFCell cell = row.getCell(column);

            if (cell == null) {
                continue;
            }

            int colspan = 1;
            for (int i = 0 ; i < getNumMergedRegions(); i++) {
                CellRangeAddress region = 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.
                        continue rows;
                    }
                    cell = row.getCell(region.getFirstColumn());
                    colspan = 1 + region.getLastColumn() - region.getFirstColumn();
                }
            }

            HSSFCellStyle style = cell.getCellStyle();
            int cellType = cell.getCellType();
            if(cellType == HSSFCell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType();

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

            if (cellType == HSSFCell.CELL_TYPE_STRING) {
                HSSFRichTextString 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) {
                        for (int j = 0; j < lines[i].length(); j++) {
                            int idx = rt.getFontAtIndex(j);
                            if (idx != 0) {
                                HSSFFont fnt = wb.getFontAt((short) idx);
                                copyAttributes(fnt, str, j, j + 1);
                            }
                        }
                    }

                    layout = new TextLayout(str.getIterator(), frc);
                    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 == HSSFCell.CELL_TYPE_NUMERIC) {
                    String dfmt = style.getDataFormatString();
                    String format = dfmt == null ? null : dfmt.replaceAll("\"", "");
                    double value = cell.getNumericCellValue();
                    try {
                        NumberFormat fmt;
                        if ("General".equals(format))
                            sval = "" + value;
                        else
                        {
                            fmt = new DecimalFormat(format);
                            sval = fmt.format(value);
                        }
                    } catch (Exception e) {
                        sval = "" + value;
                    }
                } else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
                    sval = String.valueOf(cell.getBooleanCellValue());
                }
                if(sval != null) {
                    String txt = sval + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    layout = new TextLayout(str.getIterator(), frc);
                    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());
                    }
                }
            }

        }
View Full Code Here

      return -1;
  }

    public static double getColumnWidth(XSSFSheet sheet, int column, boolean useMergedCells){
        AttributedString str;
        TextLayout layout;
        /**
         * Excel measures columns in units of 1/256th of a character width
         * but the docs say nothing about what particular character is used.
         * '0' looks to be a good choice.
         */
        char defaultChar = '0';

        /**
         * This is the multiple that the font height is scaled by when determining the
         * boundary of rotated text.
         */
        double fontHeightMultiple = 2.0;

        FontRenderContext frc = new FontRenderContext(null, true, true);

        XSSFWorkbook wb = sheet.getWorkbook();
        XSSFFont defaultFont = wb.getFontAt((short) 0);

        str = new AttributedString("" + defaultChar);
        copyAttributes(defaultFont, str, 0, 1);
        layout = new TextLayout(str.getIterator(), frc);
        int defaultCharWidth = (int)layout.getAdvance();

        double width = -1;
        rows:
        for (Iterator it = sheet.rowIterator(); it.hasNext();) {
            XSSFRow row = (XSSFRow) it.next();
            XSSFCell cell = row.getCell(column);

            if (cell == null) {
                continue;
            }

            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.
                        continue rows;
                    }
                    cell = row.getCell(region.getFirstColumn());
                    colspan = 1 + region.getLastColumn() - region.getFirstColumn();
                }
            }

            XSSFCellStyle style = cell.getCellStyle();
            int cellType = cell.getCellType();
            if(cellType == XSSFCell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType();
            XSSFFont font = wb.getFontAt(style.getFontIndex());

            if (cellType == XSSFCell.CELL_TYPE_STRING) {
                XSSFRichTextString 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) {
                        int pos = 0;
                        for (int j = 0; j < rt.numFormattingRuns(); j++) {
                            XSSFFont fnt = rt.getFontOfFormattingRun(j);
                            if (fnt != null) {
                                int len = rt.getLengthOfFormattingRun(j);
                                if(len > 0) { //ignore degenerate zero-length runs
                                    copyAttributes(fnt, str, pos, pos + len);
                                    pos += len;
                                }
                            }
                        }
                    }

                    layout = new TextLayout(str.getIterator(), frc);
                    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 == XSSFCell.CELL_TYPE_NUMERIC) {
                    String dfmt = style.getDataFormatString();
                    String format = dfmt == null ? null : dfmt.replaceAll("\"", "");
                    double value = cell.getNumericCellValue();
                    try {
                        NumberFormat fmt;
                        if ("General".equals(format))
                            sval = "" + value;
                        else
                        {
                            fmt = new DecimalFormat(format);
                            sval = fmt.format(value);
                        }
                    } catch (Exception e) {
                        sval = "" + value;
                    }
                } else if (cellType == XSSFCell.CELL_TYPE_BOOLEAN) {
                    sval = String.valueOf(cell.getBooleanCellValue());
                }
                if(sval != null) {
                    String txt = sval + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    layout = new TextLayout(str.getIterator(), frc);
                    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());
                    }
                }
            }

        }
View Full Code Here

TOP

Related Classes of java.awt.font.TextLayout

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.