Package java.awt.font

Examples of java.awt.font.TextLayout


                            FontRenderContext frc = g2.getFontRenderContext();

                            Point2D.Double pen = new Point2D.Double( 0, 0 );
                            GeneralPath gp = new GeneralPath( GeneralPath.WIND_NON_ZERO );
                            TextLayout layout = new TextLayout( sr.text, font, frc );
                            pen.y += layout.getAscent();

                            if (( fontAngle != 0 ) || sr.text.startsWith("Sono una scala verticale di prevalenza") ) {
                                AffineTransform at = new AffineTransform();
                                float width = (float)layout.getBounds().getWidth();
                                float height = (float)layout.getBounds().getHeight();

                                AffineTransform textAt = new AffineTransform();
                                textAt.translate( x, y);
                                textAt.rotate(Math.toRadians(270));
                                textAt.translate(0, height);
                                Shape shape = layout.getOutline(textAt);
                                gp.append( at.createTransformedShape( shape )/*layout.getOutline( null ))*/, false );
                                g2.draw( shape );
                            }
                            else
                                g.drawString( sr.text, x, y );
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(short 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 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++) {
                if (getMergedRegionAt(i).contains(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(getMergedRegionAt(i).getColumnFrom());
                  colspan = 1+ getMergedRegionAt(i).getColumnTo() - getMergedRegionAt(i).getColumnFrom();
                }
            }

            HSSFCellStyle style = cell.getCellStyle();
            HSSFFont font = wb.getFontAt(style.getFontIndex());

            if (cell.getCellType() == 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 (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    HSSFDataFormat dataformat = wb.createDataFormat();
                    short idx = style.getDataFormat();
                    String format = dataformat.getFormat(idx).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 (cell.getCellType() == 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

    //
    // paint the mnemonic if necessary
    //
    if ((mnemonicIndex >= 0) && (mnemonicIndex < paintText.length()))
    {
      TextLayout layout = new TextLayout(as.getIterator(),
                                         g2.getFontRenderContext());

      TextHitInfo leading = TextHitInfo.leading(mnemonicIndex);
      TextHitInfo trailing = TextHitInfo.trailing(mnemonicIndex);

      Rectangle r =
        layout.getVisualHighlightShape(leading, trailing).getBounds();

      // draw a horizontal line under the specified character to indicate
      // that it is the mnemonic.
      int left = r.x + x;
      g.drawLine(left + 1,
View Full Code Here

    public void drawString(AttributedCharacterIterator iterator, float x, float y) {
        if (inPossibleRecursion) {
            System.err.println("Called itself: drawString(AttributedCharacterIterator)");
        } else {
            inPossibleRecursion = true;
            TextLayout layout = new TextLayout(iterator, getFontRenderContext());
            layout.draw(this, x, y);
            inPossibleRecursion = false;
        }
    }
View Full Code Here

     * @return true if the font was changed, false otherwise
     */
    private boolean setFont(String family, int style, int size) {
        boolean changed = false;
        Rectangle2D rect;
        TextLayout layout;
        int s = (int)(size / 1000f);

        if (f1 == null) {
            f1 = new Font(family, style, s);
            fmt = graphics.getFontMetrics(f1);
            changed = true;
        } else {
            if ((this.style != style) ||!this.family.equals(family)
                    || this.size != s) {
                if (family.equals(this.family)) {
                    f1 = f1.deriveFont(style, (float)s);
                } else
                    f1 = new Font(family, style, s);
                fmt = graphics.getFontMetrics(f1);
                changed = true;
            }
            // else the font is unchanged from last time
        }
        if (changed) {
            layout = new TextLayout("m", f1, graphics.getFontRenderContext());
            rect = layout.getBounds();
            xHeight = (int)rect.getHeight();
        }
        // save the family and style for later comparison
        this.family = family;
        this.style = style;
View Full Code Here

        if (rt.isBold()) style |= Font.BOLD;
        if (rt.isItalic()) style |= Font.ITALIC;
        String fntname = rt.getFontName();
        Font font = new Font(fntname, style, size);

        TextLayout layout = new TextLayout(getText(), font, frc);
        int width = Math.round(layout.getAdvance());
        int height = Math.round(layout.getAscent());

        Dimension txsize = new Dimension(width, height);
        java.awt.Rectangle anchor = getAnchor();
        anchor.setSize(txsize);
        setAnchor(anchor);
View Full Code Here

  private TextLayout getTextLayout(AttributedCharacterIterator text, int committed_count) {
    AttributedString composed = new AttributedString(text, committed_count, text.getEndIndex());
    Font font = textArea.getPainter().getFont();
    FontRenderContext context = ((Graphics2D) (textArea.getPainter().getGraphics())).getFontRenderContext();
    composed.addAttribute(TextAttribute.FONT, font);
    TextLayout layout = new TextLayout(composed.getIterator(), context);
    return layout;
  }
View Full Code Here

                angle, rotateX, rotateY);
        g2.transform(rotate);

        if (useDrawRotatedStringWorkaround) {
            // workaround for JDC bug ID 4312117 and others...
            final TextLayout tl = new TextLayout(text, g2.getFont(),
                    g2.getFontRenderContext());
            tl.draw(g2, textX, textY);
        }
        else {
            // replaces this code...
            g2.drawString(text, textX, textY);
        }
View Full Code Here

            }
        }

        // We Just want it to do BIDI for us...
        // In 1.4 we might be able to use the BIDI class...
        TextLayout tl = new TextLayout(as.getIterator(), frc);

        int[] charIndices = new int[numChars];
        int[] charLevels  = new int[numChars];

        int runStart   = 0;
        int currBiDi   = tl.getCharacterLevel(0);
        charIndices[0] = 0;
        charLevels [0] = currBiDi;
        int maxBiDi    = currBiDi;

        for (int i = 1; i < numChars; i++) {
            int newBiDi = tl.getCharacterLevel(i);
            charIndices[i] = i;
            charLevels [i] = newBiDi;

            if (newBiDi != currBiDi) {
                as.addAttribute
                    (GVTAttributedCharacterIterator.TextAttribute.BIDI_LEVEL,
                     new Integer(currBiDi), runStart, i);
                runStart = i;
                currBiDi  = newBiDi;
                if (newBiDi > maxBiDi) maxBiDi = newBiDi;
            }
        }

        if ((runStart == 0) && (currBiDi==0)) {
            // This avoids all the mucking about we need to do when
            // bidi is actually performed for cases where it
            // is not actually needed.
            this.aci = this.reorderedACI = as.getIterator();
            newCharOrder = new int[numChars];
            for (int i=0; i<numChars; i++)
                newCharOrder[i] = chunkStart+i;
            return;
        }

        as.addAttribute
            (GVTAttributedCharacterIterator.TextAttribute.BIDI_LEVEL,
             new Integer(currBiDi), runStart, numChars);

        this.aci = as.getIterator();

        //  work out the new character order
        newCharOrder = doBidiReorder(charIndices, charLevels,
                                           numChars, maxBiDi);

        // construct the string in the new order
        StringBuffer reorderedString = new StringBuffer();
        char c;
        for (int i = 0; i < numChars; i++) {
            c = this.aci.setIndex(newCharOrder[i]);

            // check for mirrored char
            int bidiLevel = tl.getCharacterLevel(newCharOrder[i]);
            if ((bidiLevel & 0x01) != 0) {
                // bidi level is odd so writing dir is right to left
                // So get the mirror version of the char if there
                // is one.
                c = (char)mirrorChar(c);
View Full Code Here

    * A helper method to draw the captcha text on the generated image.
    */
    private void drawTextOnImage(Graphics2D graphics, String captchaText) {

    Font font;
    TextLayout textLayout;
    double currentFontStatus = Math.random();

    // Generate random font status.
    if (currentFontStatus >= 0.5)
    {
        font = new Font("Arial", Font.PLAIN, 60);
    }
    else
    {
        font = new Font("Arial", Font.BOLD, 60);
    }

    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    textLayout = new TextLayout(captchaText, font, graphics
        .getFontRenderContext());

    textLayout.draw(graphics, CAPTCHAConstants.TEXT_X_COORDINATE,
        CAPTCHAConstants.TEXT_Y_COORDINATE);
    }
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.