Example usage for java.awt.font TextLayout getOutline

List of usage examples for java.awt.font TextLayout getOutline

Introduction

In this page you can find the example usage for java.awt.font TextLayout getOutline.

Prototype

public Shape getOutline(AffineTransform tx) 

Source Link

Document

Returns a Shape representing the outline of this TextLayout .

Usage

From source file:Main.java

License:asdf

public Shape getTextShape(Graphics2D g2d, String str, Font font) {
    FontRenderContext frc = g2d.getFontRenderContext();
    TextLayout tl = new TextLayout(str, font, frc);
    return tl.getOutline(null);
}

From source file:FontRenderContextRenderingHints.java

public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;
    int w = getSize().width;
    int h = getSize().height;

    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2D.setRenderingHints(qualityHints);

    AffineTransform at = new AffineTransform();
    at.setToTranslation(-300, -400);/*  ww w .  j a  v  a 2  s .  c o m*/
    at.shear(-0.5, 0.0);
    FontRenderContext frc = new FontRenderContext(at, false, false);
    TextLayout tl = new TextLayout("World!", font, frc);
    Shape outline = tl.getOutline(null);
    g2D.setColor(Color.blue);

    BasicStroke wideStroke = new BasicStroke(2.0f);
    g2D.setStroke(wideStroke);
    g2D.draw(outline);

}

From source file:FontPaint.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);//from  w w w  . j av a2s . c o  m
    int width = getSize().width;
    int height = getSize().height;
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, 60);
    String s = new String("Java Source and Support.");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle outlineBounds = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(width / 2 - (outlineBounds.width / 2), height / 2 + (outlineBounds.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
}

From source file:Starry.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);/*w ww .ja v  a 2 s.  com*/
    w = getSize().width;
    h = getSize().height;
    Graphics2D g2;
    g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, w / 10);
    String s = new String("The Starry Night");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle r = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(w / 2 - (r.width / 2), h / 2 + (r.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
    g2.drawImage(img, r.x, r.y, r.width, r.height, this);

}

From source file:PrintTest.java

/**
 * This method draws the page both on the screen and the printer graphics context.
 * @param g2 the graphics context// ww  w  .  j  a v  a 2s . c om
 */
public void drawPage(Graphics2D g2) {
    FontRenderContext context = g2.getFontRenderContext();
    Font f = new Font("Serif", Font.PLAIN, 72);
    GeneralPath clipShape = new GeneralPath();

    TextLayout layout = new TextLayout("Hello", f, context);
    AffineTransform transform = AffineTransform.getTranslateInstance(0, 72);
    Shape outline = layout.getOutline(transform);
    clipShape.append(outline, false);

    layout = new TextLayout("World", f, context);
    transform = AffineTransform.getTranslateInstance(0, 144);
    outline = layout.getOutline(transform);
    clipShape.append(outline, false);

    g2.draw(clipShape);
    g2.clip(clipShape);

    final int NLINES = 50;
    Point2D p = new Point2D.Double(0, 0);
    for (int i = 0; i < NLINES; i++) {
        double x = (2 * getWidth() * i) / NLINES;
        double y = (2 * getHeight() * (NLINES - 1 - i)) / NLINES;
        Point2D q = new Point2D.Double(x, y);
        g2.draw(new Line2D.Double(p, q));
    }
}

From source file:BookTest.java

public void drawPage(Graphics2D g2, PageFormat pf, int page) {
    if (message.equals(""))
        return;// w w  w . ja  va  2  s  .com
    page--; // account for cover page

    drawCropMarks(g2, pf);
    g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
    g2.translate(-page * pf.getImageableWidth(), 0);
    g2.scale(scale, scale);
    FontRenderContext context = g2.getFontRenderContext();
    Font f = new Font("Serif", Font.PLAIN, 72);
    TextLayout layout = new TextLayout(message, f, context);
    AffineTransform transform = AffineTransform.getTranslateInstance(0, layout.getAscent());
    Shape outline = layout.getOutline(transform);
    g2.draw(outline);
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

public void init() {
    boolean emptyBackground = true;
    if (config.isUseImageBackground() && background != null) {
        ByteArrayInputStream is = new ByteArrayInputStream(background);
        JPEGImgDecoder decoder = new DefaultJPEGImgDecoder();
        try {/*from  w  w w .  ja  v a 2  s.  co  m*/
            this.image = decoder.decodeAsBufferedImage(is);
            this.width = image.getWidth();
            this.height = image.getHeight();
            emptyBackground = false;
        } catch (Exception e) {
            emptyBackground = true;
        }
    }
    if (emptyBackground) {
        this.width = config.getTextMarginLeft() * 2;
        this.height = config.getTextMarginBottom() * 6;
    }
    char[] chars = challengeId.toCharArray();
    charAttsList = new ArrayList();
    TextLayout text = null;
    AffineTransform textAt = null;
    String[] fontNames = config.getFontNames();
    for (int i = 0; i < chars.length; i++) {
        // font name
        String fontName = (fontNames.length == 1) ? fontNames[0] : fontNames[randomInt(0, fontNames.length)];

        // rise
        int rise = config.getTextRiseRange();
        if (rise > 0) {
            rise = randomInt(config.getTextMarginBottom(),
                    config.getTextMarginBottom() + config.getTextRiseRange());
        }

        if (config.getTextShear() > 0.0 || config.getTextRotation() > 0) {
            // rotation
            double dRotation = 0.0;
            if (config.getTextRotation() > 0) {
                dRotation = Math.toRadians(randomInt(-(config.getTextRotation()), config.getTextRotation()));
            }

            // shear
            double shearX = 0.0;
            double shearY = 0.0;
            if (config.getTextShear() > 0.0) {
                Random ran = new Random();
                shearX = ran.nextDouble() * config.getTextShear();
                shearY = ran.nextDouble() * config.getTextShear();
            }
            CharAttributes cf = new CharAttributes(chars[i], fontName, dRotation, rise, shearX, shearY);
            charAttsList.add(cf);
            text = new TextLayout(chars[i] + "", getFont(fontName),
                    new FontRenderContext(null, config.isFontAntialiasing(), false));
            textAt = new AffineTransform();
            if (config.getTextRotation() > 0)
                textAt.rotate(dRotation);
            if (config.getTextShear() > 0.0)
                textAt.shear(shearX, shearY);
        } else {
            CharAttributes cf = new CharAttributes(chars[i], fontName, 0, rise, 0.0, 0.0);
            charAttsList.add(cf);
        }
        if (emptyBackground) {
            Shape shape = text.getOutline(textAt);
            //                this.width += text.getBounds().getWidth();
            this.width += (int) shape.getBounds2D().getWidth();
            this.width += config.getTextSpacing() + 1;
            if (this.height < (int) shape.getBounds2D().getHeight() + rise) {
                this.height = (int) shape.getBounds2D().getHeight() + rise;
            }
        }
    }
    if (emptyBackground) {
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gfx = (Graphics2D) this.image.getGraphics();
        gfx.setBackground(Color.WHITE);
        gfx.clearRect(0, 0, width, height);
    }
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * Renders this image/*from   ww w .j a v a 2s.c  om*/
 * 
 * @return The image data
 */
private final byte[] render() throws IOException {
    Graphics2D gfx = (Graphics2D) this.image.getGraphics();
    if (config.isFontAntialiasing())
        gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int curWidth = config.getTextMarginLeft();
    FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false);
    for (int i = 0; i < charAttsList.size(); i++) {
        CharAttributes cf = (CharAttributes) charAttsList.get(i);
        TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext());
        AffineTransform textAt = new AffineTransform();
        textAt.translate(curWidth, this.height - cf.getRise());
        if (cf.getRotation() != 0) {
            textAt.rotate(cf.getRotation());
        }
        if (cf.getShearX() > 0.0)
            textAt.shear(cf.getShearX(), cf.getShearY());
        Shape shape = text.getOutline(textAt);
        curWidth += shape.getBounds().getWidth() + config.getTextSpacing();
        if (config.isUseImageBackground())
            gfx.setColor(Color.BLACK);
        else
            gfx.setXORMode(Color.BLACK);
        gfx.fill(shape);
    }
    if (config.isEffectsNoise()) {
        noiseEffects(gfx, image);
    }
    if (config.isUseTimestamp()) {
        if (config.isEffectsNoise())
            gfx.setColor(Color.WHITE);
        else
            gfx.setColor(Color.BLACK);

        TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ());
        Calendar cal = new GregorianCalendar(tz);
        SimpleDateFormat formatter;
        if (config.isUseTimestamp24hr())
            formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        else
            formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z");
        formatter.setTimeZone(tz);
        Font font = gfx.getFont();
        Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize());
        gfx.setFont(newFont);
        gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1);
    }

    return toImageData(image);
}

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

/**
 * Compute width of a single cell// w  ww .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;
}