Example usage for java.awt Graphics2D getFontMetrics

List of usage examples for java.awt Graphics2D getFontMetrics

Introduction

In this page you can find the example usage for java.awt Graphics2D getFontMetrics.

Prototype

public FontMetrics getFontMetrics() 

Source Link

Document

Gets the font metrics of the current font.

Usage

From source file:org.apache.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {// w w  w .ja  va2  s.co  m
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}

From source file:org.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {//w  w  w  . ja  v  a 2  s .c  om
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha.properties",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha.properties",
                "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha.properties", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}

From source file:Main.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();

    g2d.setColor(Color.RED);/*from  w ww. j ava 2 s.  com*/
    g2d.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);

    Font font = new Font("Arial", Font.BOLD, 48);
    g2d.setFont(font);
    FontMetrics fm = g2d.getFontMetrics();
    int x = ((getWidth() - fm.stringWidth(text)) / 2);
    int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();

    g2d.setColor(Color.BLACK);
    g2d.drawString(text, x, y);

    g2d.dispose();
}

From source file:org.springframework.cloud.stream.app.image.recognition.processor.ImageRecognitionOutputMessageBuilder.java

/**
 * Augment the input image by adding the recognized classes.
 *
 * @param imageBytes input image as byte array
 * @param result computed recognition labels
 * @return the image augmented with recognized labels.
 *///  www.  jav  a 2  s .  com
private byte[] drawLabels(byte[] imageBytes, Object result) {
    try {
        if (result != null) {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            Graphics2D g = originalImage.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            FontMetrics fm = g.getFontMetrics();

            Tuple resultTuple = new JsonStringToTupleConverter().convert(result.toString());
            ArrayList<Tuple> labels = (ArrayList) resultTuple.getValues().get(0);

            int x = 1;
            int y = 1;
            for (Tuple l : labels) {

                String labelName = l.getFieldNames().get(0);
                int probability = (int) (100 * l.getFloat(0));
                String title = labelName + ": " + probability + "%";

                Rectangle2D rect = fm.getStringBounds(title, g);

                g.setColor(bgColor);
                g.fillRect(x, y, (int) rect.getWidth() + 6, (int) rect.getHeight());

                g.setColor(textColor);
                g.drawString(title, x + 3, (int) (y + rect.getHeight() - 3));
                y = (int) (y + rect.getHeight() + 1);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(originalImage, IMAGE_FORMAT, baos);
            baos.flush();
            imageBytes = baos.toByteArray();
            baos.close();
        }
    } catch (IOException e) {
        logger.error("Failed to draw labels in the input image", e);
    }

    return imageBytes;
}

From source file:edu.ku.brc.ui.GradiantButton.java

/**
 * Paints the text of the control/*from   w  ww. j ava  2 s. c  o  m*/
 * @param g2 the graphics to be painted into
 * @param w the width of the control
 * @param h the height of the control
 * @param text the string
 */
protected void drawText(Graphics2D g2, int w, int h, String text) {
    // calculate the width and height
    int fw = g2.getFontMetrics().stringWidth(text);
    int fh = g2.getFontMetrics().getAscent() - g2.getFontMetrics().getDescent();

    int textx = this.getHorizontalAlignment() == SwingConstants.LEFT ? Math.max(getInsets().left, 2)
            : (w - fw) / 2;
    int texty = h / 2 + fh / 2;

    // draw the text
    g2.setColor(textColorShadow);
    g2.drawString(text, textx, texty);
    g2.setColor(textColor);
    g2.drawString(text, textx, texty);

}

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();
        }/*  w  ww.  j  a v a2  s. c  om*/
        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);
    }
}

From source file:de.codesourcery.planning.swing.DateAxis.java

public BoundingBox render(ITimelineCallback callback, boolean layoutOnly) {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);/*w  ww .j  a v  a  2  s. c  om*/
    cal.set(Calendar.MILLISECOND, 0);
    Date currentDate = cal.getTime();

    final Date endDate = duration.addTo(startDate);

    BoundingBox lastLabel = null;

    final int labelSpacing = 10;

    final Graphics2D graphics = callback.getGraphics();
    final int fontHeight = graphics.getFontMetrics().getHeight();

    final double scalingFactor = getXScalingFactor(callback.getBoundingBox());
    final BoundingBox box = callback.getBoundingBox();
    double x = callback.getBoundingBox().getX();
    final int tickToLabelSpacing = 2;
    final int tickLength = fontHeight;
    final int axisHeight = fontHeight + tickLength + tickToLabelSpacing;
    final double xIncrement = Math.floor(tickDuration.toSeconds() * scalingFactor);

    final Color oldColor = graphics.getColor();
    //      
    while (currentDate.compareTo(endDate) <= 0) {
        final int currentX = (int) Math.floor(x);
        if (lastLabel == null || lastLabel.getMaxX() < x) {
            final String labelText = callback.getLabelProvider().getTimelineLabel(currentDate);
            if (!StringUtils.isBlank(labelText)) {
                final Rectangle2D stringBounds = callback.getStringBounds(labelText);

                if (!layoutOnly) {
                    graphics.setColor(Color.BLACK);
                    // draw tick
                    final Stroke oldStroke = graphics.getStroke();
                    graphics.setStroke(new BasicStroke(2.0f));
                    graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                            box.getY() + fontHeight + tickToLabelSpacing);
                    graphics.setStroke(oldStroke);

                    // draw label
                    callback.drawString(Color.BLACK, currentX, box.getY(), labelText);
                }

                final BoundingBox labelBox = new BoundingBox(currentX, box.getY(),
                        currentX + (int) stringBounds.getWidth() + labelSpacing,
                        box.getY() + (int) stringBounds.getHeight());

                if (lastLabel == null) {
                    lastLabel = labelBox;
                } else {
                    lastLabel.add(labelBox);
                }

            }
        } else {
            // draw short tick
            if (!layoutOnly) {

                final int halfTickHeight = (int) Math.floor(tickLength / 2.0d);

                graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                        box.getY() + axisHeight - halfTickHeight);
            }
        }

        // draw part of axis
        if (!layoutOnly) {
            graphics.drawLine((int) x, box.getY() + axisHeight, (int) (x + xIncrement),
                    box.getY() + axisHeight);
        }
        x += xIncrement;
        currentDate = tickDuration.addTo(currentDate);
    }

    callback.getGraphics().setColor(oldColor);
    final BoundingBox result = lastLabel != null ? lastLabel : new BoundingBox(0, 0, 0, 0);
    result.incHeight(axisHeight);
    return result;
}

From source file:uk.co.real_logic.aeron.tools.perf_tools.AeronLatencyUnderLoadPublisher.java

private void generateScatterPlot() throws IOException {
    final BufferedImage image = new BufferedImage(1800, 1000, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = image.createGraphics();
    final FontMetrics fm = g2.getFontMetrics();
    final String filename = "throughputency.png";
    final File imageFile = new File(filename);

    final int height = 940;
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    for (final long timestamp : timestamps) {
        final double ts = timestamp / 1000.0;
        if (ts < min) {
            min = ts;//from  w  w  w .ja  v a2 s  .c om
        }
        if (ts > max) {
            max = ts;
        }
    }
    final double stepY = height / max;

    g2.setColor(Color.white);
    g2.fillRect(0, 0, 1800, 1000);
    g2.setColor(Color.black);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString("Latency ScatterPlot (microseconds)",
            900 - fm.stringWidth("Latency ScatterPlot (microseconds)") / 2, 20);
    g2.drawString("" + max, 10, 20);
    g2.drawLine(100, 20, 100, 960);
    g2.drawLine(100, 960, 1790, 960);
    int start = 0;
    int end = 100;
    final double width = 1690.0 / 7.0;
    g2.setColor(Color.red);
    plotSubset(g2, start, end, "10 msgs/sec", 100, width, stepY, means[0]);

    start = 100;
    end = 1100;
    g2.setColor(Color.green);
    plotSubset(g2, start, end, "100 msgs/sec", 100 + width, width, stepY, means[1]);

    start = 1100;
    end = 11100;
    g2.setColor(Color.blue);
    plotSubset(g2, start, end, "1K msgs/sec", 100 + width * 2, width, stepY, means[2]);

    start = 11100;
    end = 111100;
    g2.setColor(Color.cyan);
    plotSubset(g2, start, end, "10K msgs/sec", 100 + width * 3, width, stepY, means[3]);

    start = 111100;
    end = 1111100;
    g2.setColor(Color.magenta);
    plotSubset(g2, start, end, "100K msgs/sec", 100 + width * 4, width, stepY, means[4]);

    start = 1111100;
    end = 11111100;
    g2.setColor(Color.yellow);
    plotSubset(g2, start, end, "1M msgs/sec", 100 + width * 5, width, stepY, means[5]);

    start = 11111100;
    end = 41111100;
    g2.setColor(Color.orange);
    plotSubset(g2, start, end, "3M msgs/sec", 100 + width * 6, width, stepY, means[6]);

    ImageIO.write(image, "png", imageFile);
}

From source file:org.cybercat.automation.addons.common.ScreenshotManager.java

public BufferedImage applySubs(BufferedImage image, String text) {
    Graphics2D g2 = image.createGraphics();
    g2.setFont(font);// w w w  .  j a  v a  2  s .  c om

    int height = image.getHeight();
    int width = image.getWidth();

    g2.setColor(fontColor);

    String[] subs = text.split("\n");
    FontMetrics fMetrics = g2.getFontMetrics();
    int lineHeight = fMetrics.getHeight();
    int lineWidth;
    for (int i = subs.length; i > 0; i--) {
        lineWidth = fMetrics.stringWidth(subs[i - 1]);
        int y = height - bottomOffset - ((subs.length - i) * (lineHeight + lineOffset));
        int x = (width / 2) - (lineWidth / 2);
        g2.drawString(subs[i - 1], x, y);
    }
    g2.dispose();
    return image;
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

/**
 * Draws a single character.//from   w ww. j  av a2  s .c o  m
 *
 * @param g2d
 *            {@link Graphics2D} context
 * @param ch
 *            character to draw
 * @param x
 *            left x position of the character
 * @param boxWidth
 *            width of the box
 */
private void drawCharacter(Graphics2D g2d, char ch, int x, int boxWidth) {
    double degree = (rnd.nextDouble() * rotationAmplitude * 2) - rotationAmplitude;
    double scale = 1 - (rnd.nextDouble() * scaleAmplitude / 100);

    Graphics2D cg2d = (Graphics2D) g2d.create();
    cg2d.setFont(font.deriveFont(fontSize));

    cg2d.translate(x + (boxWidth / 2), height / 2);
    cg2d.rotate(degree * PI / 90);
    cg2d.scale(scale, scale);

    FontMetrics fm = cg2d.getFontMetrics();
    int charWidth = fm.charWidth(ch);
    int charHeight = fm.getAscent() + fm.getDescent();

    cg2d.drawString(String.valueOf(ch), -(charWidth / 2), fm.getAscent() - (charHeight / 2));

    cg2d.dispose();
}