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.squidy.designer.zoom.impl.InformationShape.java

@Override
protected void paintShapeZoomedIn(PPaintContext paintContext) {
    super.paintShapeZoomedIn(paintContext);

    if (informationSource != null) {
        Graphics2D g = paintContext.getGraphics();

        PBounds bounds = getBoundsReference();
        double x = bounds.getX();
        double width = bounds.getWidth();

        String source = "Source: " + informationSource;

        g.setFont(fontName);/*www.j  a va 2 s . co m*/
        g.drawString(name, (int) (x + 50), 230);

        g.setFont(fontSource);
        source = FontUtils.createCroppedLabelIfNecessary(g.getFontMetrics(), source, (int) width);
        g.drawString(source, (int) (x + width - FontUtils.getWidthOfText(g.getFontMetrics(), source)) - 20,
                130);
    }
}

From source file:org.csml.tommo.sugar.modules.MappingQuality.java

protected void drawColumnHeader(Graphics2D g2, final MappingQualityTableModel model, int imgSize,
        int topBottomSeparator, int height, StringBuffer d) {

    // draw Top-Bottom header
    if (model.getTopBottomSeparatorColumn() > 0) {
        String s = "Top-Bottom";
        int stringWidth = g2.getFontMetrics().stringWidth(s);
        g2.drawString(s, 1 + imgSize * (model.getTopBottomSeparatorColumn() + 1)
                + (topBottomSeparator - 1 - stringWidth) / 2, 1 + height + 10 - 3);
    }//from   ww  w. j ava 2  s. co  m

    int separator = 0;
    for (int c = 0; c < model.getColumnCount(); c++) {
        d.append(model.getColumnName(c));
        d.append("\t");

        if (c == model.getTopBottomSeparatorColumn()) {
            d.append("Top-Bottom");
            d.append("\t");
        }
        Integer[] tiles = model.getTilesForColumn(c);
        for (int i = 0; i < tiles.length; i++) {
            String s = tiles[i].toString();
            int stringWidth = g2.getFontMetrics().stringWidth(s);
            g2.drawString(s, 1 + imgSize * c + (imgSize - 1 - stringWidth) / 2 + separator,
                    1 + height + 10 * (i + 1) - 3);
        }
        if (c == model.getTopBottomSeparatorColumn()) {
            separator = topBottomSeparator;
        }
    }
    d.append("\n");
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode.java

/**
 * Draw a GraphNode as a rectangle with a name
 *
 * @param g   The Java2D Graphics//from www  .  ja  va 2  s .  c  o m
 * @param col The color to draw
 */
public void drawNode(final Graphics2D g, final Color col) {
    final int x = displayPosition.x;
    final int y = displayPosition.y;

    g.setFont(g.getFont().deriveFont(Font.BOLD, 11));
    final FontMetrics metrics = g.getFontMetrics();
    final String name = node.getId();
    final Rectangle2D rect = metrics.getStringBounds(name, g);
    final int stringWidth = (int) rect.getWidth();
    setSize(Math.max(stringWidth, 50) + 10, 25);

    int step = 4;
    int alpha = 96;
    for (int i = 0; i < step; ++i) {
        g.setColor(new Color(0, 0, 0, alpha - (32 * i)));
        g.drawLine(x + i + 1, y + nodeHeight + i, x + nodeWidth + i - 1, y + nodeHeight + i);
        g.drawLine(x + nodeWidth + i, y + i, x + nodeWidth + i, y + nodeHeight + i);
    }

    Shape clipShape = new Rectangle(x, y, nodeWidth, nodeHeight);

    g.setComposite(AlphaComposite.SrcAtop);
    g.setPaint(new GradientPaint(x, y, col, x + nodeWidth, y + nodeHeight, col.darker()));
    g.fill(clipShape);

    g.setColor(Color.blue);
    g.draw3DRect(x, y, nodeWidth - 1, nodeHeight - 1, true);

    g.setColor(Color.BLACK);
    g.drawString(name, x + (nodeWidth - stringWidth) / 2, y + 15);
}

From source file:savant.amino.AminoCanvas.java

private void paintAminoAcid(Graphics2D g2, AminoAcid a, int pos, int bases, int labelPos, boolean labelled) {
    if (a != null) {
        g2.setColor(new Color(a.color.getRed(), a.color.getGreen(), a.color.getBlue(), plugin.getAlpha()));
        double x0 = track.transformXPos(pos);
        double x1 = track.transformXPos(pos + bases);
        g2.fill(new Rectangle2D.Double(x0, 0.0, x1 - x0, getHeight()));
        if (labelled) {
            g2.setColor(a == AminoAcid.STOP ? Color.WHITE : Color.BLACK);
            double charWidth = g2.getFontMetrics().charWidth(a.code);
            g2.drawString(Character.toString(a.code),
                    (float) (track.transformXPos(labelPos) + track.transformXPos(labelPos + 3) - charWidth)
                            * 0.5F,// w  ww.  j ava  2 s .c  o m
                    getHeight() * 0.5F);
        }
    }
}

From source file:com.stanley.captioner.Transcriber.java

public void start() {
    // Create stream speech recognizer.
    StreamSpeechRecognizer recognizer = null;
    try {//w  w w.ja  va  2 s  . c  o m
        recognizer = new StreamSpeechRecognizer(config);
    } catch (IOException e) {
        System.out.println("Failed to create recognizer.");
    }

    // Open print writer for writing text output.
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(textOut);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to create print writer.");
    }

    // Open stream for first pass.
    InputStream stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Initialize loop variables.
    SpeechResult result;
    int resultCount = 0;
    Stats stats = recognizer.createStats(1);

    // Start recognizer for first pass.
    recognizer.startRecognition(stream);
    System.out.println("First pass (stats collection) started.");

    // First pass loop to collect statistics for model adaptation.
    while ((result = recognizer.getResult()) != null) {
        try {
            stats.collect(result);
        } catch (Exception e) {
            System.out.println("Failed to collect stats.");
        }

        resultCount++;

        // Toggle for testing.
        if (quickTest && resultCount > 5) {
            break;
        }
    }
    // Close recognizer (end of first pass).
    recognizer.stopRecognition();
    System.out.println("Stats collection stopped.");

    // Transform model using model adaptation.
    Transform transform = stats.createTransform();
    recognizer.setTransform(transform);

    // Reopen stream for second pass.
    stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Start recognizer for second pass.
    recognizer.startRecognition(stream);
    System.out.println("Second pass started.");

    // Create output text file header.
    writer.printf("%-20s", "WORD:");
    writer.printf("%20s", "CONFIDENCE:");
    writer.printf("%20s", "START TIME:");
    writer.printf("%20s", "END_TIME:");
    writer.println();
    for (int i = 0; i < 80; i++) {
        writer.print("-");
    }
    writer.println();

    // Initialize loop variables.
    int wordCount = 0;
    String sentence = "";
    int sentenceLength = 0;
    long sentenceStart = 0;
    long sentenceEnd = 0;
    ArrayList<Sentence> sentences = new ArrayList<>();

    // Second pass loop to calculate sentences.
    RECOG: while ((result = recognizer.getResult()) != null) {
        for (WordResult wordResult : result.getWords()) {
            wordCount++;
            String word = wordResult.getWord().toString();
            double confidence = wordResult.getConfidence();
            long startTime = wordResult.getTimeFrame().getStart();
            long endTime = wordResult.getTimeFrame().getEnd();
            writer.printf("%-20s", word);
            writer.printf("%20.1f", confidence);
            writer.printf("%20d", startTime);
            writer.printf("%20d", endTime);
            writer.println();

            if (sentenceLength + word.length() < 40) {
                // Add to current sentence.
                sentence += " " + word;
                sentenceLength += word.length();
                sentenceEnd = endTime;
            } else {
                // End of current sentence, store and start a new one.
                sentences.add(new Sentence(sentence, sentenceStart, sentenceEnd));
                sentenceStart = sentenceEnd;
                sentence = "";
                sentenceLength = 0;
            }

            // Toggle for testing.
            if (quickTest && wordCount > 50) {
                break RECOG;
            }
        }
    }

    // Close print writer and recognizer (end of second pass).
    writer.close();
    recognizer.stopRecognition();
    System.out.println("Second pass stopped.");

    // Create folder for caption images.
    String imageDirPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()));
    System.out.println(imageDirPath);
    File imageDir = new File(imageDirPath);
    if (!imageDir.exists()) {
        // Create the folder if it doesn't already exist.
        imageDir.mkdir();
    }

    // Calculate video output path.
    String videoOutPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()) + ".mp4");
    System.out.println(videoOutPath);

    // Initialize a command string for overlaying the captions.
    String commandString = String.format("%s -y -loglevel quiet -i %s", new Converter().getFFmpegPath(),
            videoIn.getAbsolutePath());
    System.out.println(commandString);

    // Initialize a complex filter for overlaying the captions.
    String filterString = "-filter_complex";

    // Acquire a probe object for collecting video details.
    Converter converter = new Converter();
    FFprobe ffprobe = null;
    try {
        ffprobe = new FFprobe(converter.getFFprobePath());
    } catch (IOException e) {
        System.out.println("Failed to find ffprobe.");
    }

    // Probe the video for details.
    FFmpegProbeResult probeResult = null;
    try {
        probeResult = ffprobe.probe(videoIn.getAbsolutePath());
    } catch (IOException e) {
        System.out.println("Failed to probe video file.");
    }

    // Get the width and height of the video.
    FFmpegStream videoStream = probeResult.getStreams().get(0);
    int videoWidth = videoStream.width;
    int videoHeight = videoStream.height;

    // Calculate the x and y coordinates of the captions.
    int captionX = (videoWidth / 2) - 220;
    int captionY = videoHeight - 25 - 10;

    // Loop over the sentences, generate captions, and build command string.
    int k = 0;
    for (Sentence s : sentences) {
        // Create caption image from sentence.
        BufferedImage bi = new BufferedImage(440, 50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        g.setPaint(new Color(0, 0, 0, 128));
        g.fillRect(0, 0, 440, 50);
        g.setPaint(new Color(255, 255, 255, 255));
        g.setFont(new Font("Serif", Font.BOLD, 20));
        FontMetrics fm = g.getFontMetrics();
        int x = bi.getWidth() - fm.stringWidth(s.text) - 5;
        int y = fm.getHeight() - 5;
        g.drawString(s.text, x, y);
        g.dispose();

        // Write the image to file for future reference.
        String suffix = String.format("caption-%03d.png", k);
        String imagePath = FilenameUtils.concat(imageDirPath, suffix);
        try {
            File imageFile = new File(imagePath);
            ImageIO.write(bi, "png", imageFile);
        } catch (IOException e) {
            System.out.println("Failed to write caption image to file.");
        }

        // Add the caption image path to the command string.
        commandString += " -i " + imagePath;

        // Add an entry to the complex filter with the caption timeframe.
        if (k == 0) {
            filterString += String.format(" \"[0:v][1:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", captionX,
                    captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        } else {
            filterString += String.format(" [tmp][%d:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", k + 1,
                    captionX, captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        }
        k++;
    }

    // Build final command string.
    String finalCommand = String.format("%s %s -codec:a copy %s", commandString, filterString, videoOutPath);

    System.out.println(finalCommand);

    // Attempt to run the final command string to embed the captions.
    try {
        Process p = Runtime.getRuntime().exec(finalCommand);
        try {
            if (p.waitFor() != 0) {
                // Embedding the captions failed.
                System.out.println("Image overlay failed.");
            }
        } catch (InterruptedException e) {
            // Embedding the captions was interrupted.
            System.out.println("Interrupted image overlay.");
        }
    } catch (IOException e) {
        // Command string failed to execute.
        System.out.println("Failed to execute image overlay.");
    }

    // Delete intermediate audio file.
    audio.delete();

    System.out.println("........................CAPTIONING COMPLETE........................");
}

From source file:com.quinsoft.zeidon.objectbrowser.EntitySquare.java

private void paintCenteredText(Graphics2D graphics2, int y, String text, Color color) {
    Color prevColor = graphics2.getColor();
    if (color != null)
        graphics2.setColor(color);//from   www  . j  a va2s  .c o  m

    FontMetrics fm = graphics2.getFontMetrics();

    String lines[] = text.split("\n");

    // Adjust y if there is more than one line.
    y -= (lines.length - 1) * fm.getHeight() / 2;

    for (String line : lines) {
        int lth = fm.stringWidth(line);
        int mid = size.width / 2;
        graphics2.drawString(line, mid - lth / 2, y);
        y += fm.getHeight();
    }

    if (color != null)
        graphics2.setColor(prevColor);
}

From source file:org.squidy.designer.zoom.impl.VisualizationShape.java

/**
 * @param paintContext/* w  w w.  ja  va2 s. c  o  m*/
 */
protected void paintHeadline(PPaintContext paintContext) {

    Graphics2D g = paintContext.getGraphics();

    g.setFont(fontHeadline);
    FontMetrics fm = g.getFontMetrics();

    PBounds bounds = getBoundsReference();
    double x = bounds.getX();
    double width = bounds.getWidth();

    int titleWidth = FontUtils.getWidthOfText(fm, getTitle());
    g.drawString(getTitle(), (int) (x + width / 2) - (titleWidth / 2), 100);

    int breadcrumbWidth = FontUtils.getWidthOfText(fm, getBreadcrumb());
    g.drawString(getBreadcrumb(), (int) (x + width / 2) - (breadcrumbWidth / 2), 100 + fm.getHeight());
}

From source file:org.squidy.designer.zoom.impl.VisualizationShape.java

/**
 * @param paintContext//from w w  w. java2s  . com
 */
protected void paintNodeLabels(PPaintContext paintContext) {

    Graphics2D g = paintContext.getGraphics();

    g.setFont(g.getFont().deriveFont(18f));
    FontMetrics fm = g.getFontMetrics();

    PBounds bounds = getBoundsReference();
    double width = bounds.getWidth();
    double height = bounds.getHeight();

    String inputName = pipeShape.getSource().getTitle();
    rotation270.setToRotation(Math.toRadians(270));
    paintContext.pushTransform(rotation270);
    g.setColor(Color.WHITE);
    g.drawString(inputName, (int) -((height / 2) + (FontUtils.getWidthOfText(fm, inputName) / 2)), -25);
    paintContext.popTransform(rotation270);

    String outputName = pipeShape.getTarget().getTitle();
    rotation90.setToRotation(Math.toRadians(90));
    paintContext.pushTransform(rotation90);
    g.setColor(Color.WHITE);
    g.drawString(outputName, (int) ((height / 2) - (FontUtils.getWidthOfText(fm, outputName) / 2)),
            (int) (-width - 30));
    paintContext.popTransform(rotation90);
}

From source file:nl.b3p.kaartenbalie.core.server.b3pLayering.ConfigLayer.java

protected void drawMessageBox(Graphics2D g2d, String message, int x, int y, int w, int h) {
    drawEdgedBox(g2d, x, y, w, h);/*from  w ww  . j  a v  a2s.  co m*/

    if (message == null) {
        message = "null";
    }

    /*
     * Padding...
     */
    x += KBConfiguration.OHD_padding;
    y += KBConfiguration.OHD_padding;
    w -= KBConfiguration.OHD_padding;
    h -= KBConfiguration.OHD_padding;

    g2d.setFont(KBConfiguration.OHD_messageBoxFont);
    g2d.setColor(KBConfiguration.OHD_fontBoxColor);
    FontMetrics fm = g2d.getFontMetrics();

    int fontHeight = KBConfiguration.OHD_messageBoxFont.getSize();
    int yOffset = y;
    String[] lines = message.split("\n");
    for (int j = 0; j < lines.length; j++) {
        String[] words = lines[j].split(" ");
        String line = "";
        for (int i = 0; i < words.length; i++) {
            String testLine = new String(line + " " + words[i]);
            Rectangle2D testRectangle = fm.getStringBounds(testLine, g2d);
            if (testRectangle.getWidth() > w) {
                conditionalWrite(g2d, line, x, yOffset + fontHeight, y + h);
                line = words[i];
                yOffset += fontHeight;
            } else {
                line = testLine;
            }
        }
        conditionalWrite(g2d, line, x, yOffset + fontHeight, y + h);
        yOffset += (fontHeight + KBConfiguration.OHD_lineSpacing);
    }

}

From source file:com.aurel.track.report.gantt.data.TrackGanttRenderer.java

/** Prints the specified labelstring.
 * The x coordinate specifies the startposition.
 * The y coordinate specifies the lower startposition of the label.
 * If alignRight is true, this method subtracts the length of the 
 * labelstring and 3 pixels from the x coordinate.
 * Otherwise it adds 3 pixels to the x coordinate.
 *///  w  ww.j  av  a2s . com
private void drawLabel(String s, Graphics2D g2, int _x, int _y, Font f, boolean alignRight) {

    g2.setPaint(Color.black);
    g2.setFont(f);

    int x = 0;

    if (alignRight) {
        // subtract the length neede to print the label from the x coordinate
        x = _x - g2.getFontMetrics().stringWidth(s) - 3;
    } else {
        x = _x + 3;
    }

    // correct the very first and very last point in the diagram.
    if (startLabels > x) {
        startLabels = x;
    }

    if (stopLabels < x + g2.getFontMetrics().stringWidth(s)) {
        stopLabels = x + g2.getFontMetrics().stringWidth(s);
    }

    g2.drawString(s, x, _y);

}