Package java.awt.font

Examples of java.awt.font.TextLayout


        getEscherGraphics().drawString(string, x, y);
    }

    public void drawString(AttributedCharacterIterator attributedcharacteriterator, float x, float y)
    {
        TextLayout textlayout = new TextLayout(attributedcharacteriterator, getFontRenderContext());
        Paint paint1 = getPaint();
        setColor(getColor());
        fill(textlayout.getOutline(AffineTransform.getTranslateInstance(x, y)));
        setPaint(paint1);
    }
View Full Code Here


        txt.setWordWrap(TextBox.WrapNone);
        txt.setHorizontalAlignment(TextBox.AlignLeft);
        txt.setVerticalAlignment(TextBox.AnchorMiddle);


        TextLayout layout = new TextLayout(s, font, getFontRenderContext());
        float ascent = layout.getAscent();

        float width = (float) Math.floor(layout.getAdvance());
        /**
         * Even if top and bottom margins are set to 0 PowerPoint
         * always sets extra space between the text and its bounding box.
         *
         * The approximation height = ascent*2 works good enough in most cases
View Full Code Here

            if (_shape.getWordWrap() == TextShape.WrapNone) {
                wrappingWidth = _shape.getSheet().getSlideShow().getPageSize().width;
            }

            TextLayout textLayout = measurer.nextLayout(wrappingWidth + 1,
                    nextBreak == -1 ? paragraphEnd : nextBreak, true);
            if (textLayout == null) {
                textLayout = measurer.nextLayout(textWidth,
                    nextBreak == -1 ? paragraphEnd : nextBreak, false);
            }
            if(textLayout == null){
                logger.log(POILogger.WARN, "Failed to break text into lines: wrappingWidth: "+wrappingWidth+
                        "; text: " + rt.getText());
                measurer.setPosition(rt.getEndIndex());
                continue;
            }
            int endIndex = measurer.getPosition();

            float lineHeight = (float)textLayout.getBounds().getHeight();
            int linespacing = rt.getLineSpacing();
            if(linespacing == 0) linespacing = 100;

            TextElement el = new TextElement();
            if(linespacing >= 0){
                el.ascent = textLayout.getAscent()*linespacing/100;
            } else {
                el.ascent = -linespacing*Shape.POINT_DPI/Shape.MASTER_DPI;
            }

            el._align = rt.getAlignment();
            el.advance = textLayout.getAdvance();
            el._textOffset = textOffset;
            el._text = new AttributedString(it, startIndex, endIndex);
            el.textStartIndex = startIndex;
            el.textEndIndex = endIndex;

            if (prStart){
                int sp = rt.getSpaceBefore();
                float spaceBefore;
                if(sp >= 0){
                    spaceBefore = lineHeight * sp/100;
                } else {
                    spaceBefore = -sp*Shape.POINT_DPI/Shape.MASTER_DPI;
                }
                el.ascent += spaceBefore;
            }

            float descent;
            if(linespacing >= 0){
                descent = (textLayout.getDescent() + textLayout.getLeading())*linespacing/100;
            } else {
                descent = -linespacing*Shape.POINT_DPI/Shape.MASTER_DPI;
            }
            if (prStart){
                int sp = rt.getSpaceAfter();
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

        String strText = this._strWallPaper_;
       
        if (strText == null)
            strText = System.getProperty(GfrEnuSystemPropertiesKeys.NAME_LONG_APPLI.getLabel());
       
        TextLayout tlt = new TextLayout(strText,
                GfrUtilFont.s_get(Font.BOLD, 10),
                new FontRenderContext(null,
                false, false));
       
        int sw = (int) tlt.getBounds().getWidth();
        int sh = (int) (tlt.getAscent() + tlt.getDescent());
        BufferedImage bi = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_RGB);
        Graphics2D tG2 = bi.createGraphics();
        tG2.setBackground(GfrColor.WHITE_2);
        tG2.clearRect(0, 0, sw, sh);
        tG2.setColor(GfrColor.GRAY_8);
        tlt.draw(tG2, 0, tlt.getAscent());
        Rectangle r = new Rectangle(0, 0, sw, sh);
        return new TexturePaint(bi, r);
    }
View Full Code Here

       
       
        FontRenderContext frc = g2.getFontRenderContext();
        Font fnt = new Font("sansserif", this._intFontStyle_, 32);
        String str = this._strText_;
        TextLayout tl = new TextLayout(str, fnt, frc);
        double sw = tl.getBounds().getWidth();
        double sh = tl.getBounds().getHeight(); sh *=2;
        double sx = (w - 40) / sw;
        double sy = (h - 40) / sh;
        AffineTransform Tx = AffineTransform.getScaleInstance(sx, sy);
        Shape shape = tl.getOutline(Tx);
        sw = shape.getBounds().getWidth();
        sh = shape.getBounds().getHeight();
        Tx =
                AffineTransform.getTranslateInstance(w / 2 - sw / 2, h / 2 + sh
                / 2);
        shape = Tx.createTransformedShape(shape);
        Rectangle r = shape.getBounds();

        if (doClip) {
            g2.clip(shape);
        }

        if (clipType.equals("Lines")) {
            g2.setColor(Color.BLACK);
            g2.fill(r);
            g2.setColor(GfrColor.YELLOW);
            g2.setStroke(new BasicStroke(1.5f));
            for (int j = r.y; j < r.y + r.height; j = j + 3) {
                Line2D line = new Line2D.Float(r.x, j,
                        (r.x + r.width), j);
                g2.draw(line);
            }
        } else if (clipType.equals("Image")) {
            g2.drawImage(_IMG_, r.x, r.y, r.width, r.height, null);
        } else if (clipType.equals("TP")) {
            g2.setPaint(_TEXTURE_PAINT_);
            g2.fill(r);
        } else if (clipType.equals("GP")) {
            g2.setPaint(new GradientPaint(0, 0, GfrColor.GREEN, w, h, GfrColor.BLUE));
            g2.fill(r);
        } else if (clipType.equals("Text")) {
            g2.setColor(Color.BLACK);
            g2.fill(shape.getBounds());
            g2.setColor(GfrColor.CYAN);
            fnt = new Font("serif", this._intFontStyle_, 10);
            tl = new TextLayout("java", fnt, frc);
            sw = tl.getBounds().getWidth();

            int x = r.x;
            int y = (int) (r.y + tl.getAscent());
            sh = r.y + r.height;
            while (y < sh) {
                tl.draw(g2, x, y);
                if ((x += (int) sw) > (r.x + r.width)) {
                    x = r.x;
                    y += (int) tl.getAscent();
                }
            }
        }
        g2.setClip(new Rectangle(0, 0, w, h));

View Full Code Here

    this.margin = margin;
    width = this.margin * 2;
    height = this.margin * 2;
    char[] chars = challengeId.toCharArray();
    charAttsList = new ArrayList();
    TextLayout text;
    AffineTransform textAt;
    Shape shape;
    for (int i = 0; i < chars.length; i++)
    {
      String fontName = (String)fontNames.get(randomInt(0, fontNames.size()));
      double rotation = Math.toRadians(randomInt(-35, 35));
      int rise = randomInt(margin / 2, margin);
      Random ran = new Random();
      double shearX = ran.nextDouble() * 0.2;
      double shearY = ran.nextDouble() * 0.2;
      CharAttributes cf = new CharAttributes(chars[i], fontName, rotation, rise, shearX,
        shearY);
      charAttsList.add(cf);
      text = new TextLayout(chars[i] + "", getFont(fontName), new FontRenderContext(null,
        false, false));
      textAt = new AffineTransform();
      textAt.rotate(rotation);
      textAt.shear(shearX, shearY);
      shape = text.getOutline(textAt);
      width += (int)shape.getBounds2D().getWidth();
      if (height < (int)shape.getBounds2D().getHeight() + rise)
      {
        height = (int)shape.getBounds2D().getHeight() + rise;
      }
View Full Code Here

      gfx.setBackground(Color.WHITE);
      int curWidth = margin;
      for (int i = 0; i < charAttsList.size(); i++)
      {
        CharAttributes cf = (CharAttributes)charAttsList.get(i);
        TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()),
          gfx.getFontRenderContext());
        AffineTransform textAt = new AffineTransform();
        textAt.translate(curWidth, height - cf.getRise());
        textAt.rotate(cf.getRotation());
        textAt.shear(cf.getShearX(), cf.getShearY());
        Shape shape = text.getOutline(textAt);
        curWidth += shape.getBounds().getWidth();
        gfx.setXORMode(Color.BLACK);
        gfx.fill(shape);
      }
View Full Code Here

            // 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: this won't occur for the English text in this sample.
                // Note: drawPosX is always where the LEFT of the text is placed.
                float drawPosX = layout.isLeftToRight()
                        ? (0 + destx) : breakWidth - layout.getAdvance();

                // 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();
            }

            g2d.dispose();
            lineMeasurer = null;
View Full Code Here

                // Get lines until the entire paragraph has been displayed.
                while (lmCopy.getPosition() < paragraphEnd) {

                    // Retrieve next layout. A cleverer program would also cache
                    // these layouts until the component is re-sized.
                    TextLayout layout = lmCopy.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: this won't occur for the English text in this sample.
                    // Note: drawPosX is always where the LEFT of the text is placed.
                    // TODO adjust the RightToLeft case with destx also
                    // LeftToRight has been fixed
                    rectPosX = layout.isLeftToRight()
                            ? (0 + destx) : breakWidth - layout.getAdvance();
                    // Move y-coordinate by the ascent of the layout.
                    rectPosY += layout.getAscent();
                    // Draw the TextLayout at (drawPosX, drawPosY).
                    // layout.draw(g2d, drawPosX, drawPosY);
                    // Move y-coordinate in preparation for next layout.
                    rectPosY += layout.getDescent() + layout.getLeading();
                    // add the y move to rectangle height
                    System.out.println("rectHeight was " + rectHeight);
                    rectHeight += layout.getAscent() + layout.getDescent() +
                            layout.getLeading();
                    System.out.println("rectHeight is now " + rectHeight);
                    // if text line width is greater than rectWidth
                    // set rectWidth to line width
                    if (layout.getAdvance() > rectWidth) {
                        rectWidth = layout.getAdvance();
                    }
                }

                System.out.println("rectangle position and size= " +
                        rectPosX + ", " + desty + ", " +
                        rectWidth + ", " + rectHeight);
                // draw a rectangle around text with padding
                g2d.fill(new RoundRectangle2D.Double((destx - 4) , (desty - 4),
                        (rectWidth + 8),
                        (rectHeight + 8), 10, 10));

                // finish
                lmCopy = null;
                rectMeasurer = null;

                // end text rectangle

                // color for text
                g2d.setColor(itModel.getColor());

                // Create a new LineBreakMeasurer from the paragraph.
                // It will be cached and re-used.
                if (lineMeasurer == null) {
                    AttributedCharacterIterator paragraph = attStr.getIterator();
                    paragraphStart = paragraph.getBeginIndex();
                    paragraphEnd = paragraph.getEndIndex();
                    FontRenderContext frc = g2d.getFontRenderContext();
                    lineMeasurer = new LineBreakMeasurer(paragraph, frc);
                }

                // Set break width to width of Component.
                breakWidth = itModel.getTextBoxWidth();
                float drawPosY = desty;
                // 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: this won't occur for the English text in this sample.
                    // Note: drawPosX is always where the LEFT of the text is placed.
                    // TODO adjust the RightToLeft case with destx also
                    // LeftToRight has been fixed
                    float drawPosX = layout.isLeftToRight()
                            ? (0 + destx) : breakWidth - layout.getAdvance();

                    // 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();


                }

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.