List of usage examples for java.awt Graphics2D setFont
public abstract void setFont(Font font);
From source file:io.github.karols.hocr4j.PageRenderer.java
/** * Renders this page on the given image. * The image is modified, not copied./* www . ja v a 2 s.c o m*/ * * @param page page to render */ public void renderOnTop(@Nonnull Page page, @Nonnull BufferedImage img) { Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(Color.RED); for (Area a : page) { for (Paragraph p : a) { for (Line l : p) { for (Word w : l.words) { if (w.isBold()) { if (w.isItalic()) { g.setFont(boldItalicFont); } else { g.setFont(boldFont); } } else if (w.isItalic()) { g.setFont(italicFont); } else { g.setFont(plainFont); } Bounds b = w.getBounds().scale(scale); g.drawString(w.getText(), b.getLeft(), b.getBottom()); } } } } g.setStroke(new BasicStroke(strokeWidth)); g.setColor(defaultRectangleColor); for (Bounds rect : rectanglesToDraw) { if (rect != null) { Bounds b = rect.scale(scale); g.drawRect(b.getLeft(), b.getTop(), b.getWidth(), b.getHeight()); } } for (Pair<Color, Bounds> rect : coloredRectanglesToDraw) { if (rect != null) { g.setColor(rect.getLeft()); Bounds b = rect.getRight().scale(scale); g.drawRect(b.getLeft(), b.getTop(), b.getWidth(), b.getHeight()); } } }
From source file:com.stanley.captioner.Transcriber.java
public void start() { // Create stream speech recognizer. StreamSpeechRecognizer recognizer = null; try {/*from w w w . ja v a 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.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. *///from ww w .ja va 2s . c o m 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); }
From source file:com.alibaba.simpleimage.render.CornerDrawTextItem.java
@Override public void drawText(Graphics2D graphics, int width, int height) { if (StringUtils.isBlank(text)) { return;//w ww . j a v a 2 s. com } int x = 0, y = 0; // ? int textLength = (int) (width * textWidthPercent); // ?? int fontsize = textLength / text.length(); // ?.....? if (fontsize < minFontSize) { return; } float fsize = (float) fontsize; Font font = defaultFont.deriveFont(fsize); graphics.setFont(font); FontRenderContext context = graphics.getFontRenderContext(); int sw = (int) font.getStringBounds(text, context).getWidth(); // ?? if (width > height) { y = height / 4; } else { y = width / 4; } int halflen = sw / 2; if (halflen <= (y - fontsize)) { x = y - halflen; } else { x = fontsize; } if (x <= 0 || y <= 0) { return; } if (fontShadowColor != null) { graphics.setColor(fontShadowColor); graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize)); } graphics.setColor(fontColor); graphics.drawString(text, x, y); if (width > height) { y = height - (height / 4); } else { y = height - (width / 4); } halflen = sw / 2; if (halflen <= (height - y - fontsize)) { x = width - (height - y) - halflen; } else { x = width - sw - fontsize; } if (x <= 0 || y <= 0) { return; } if (fontShadowColor != null) { graphics.setColor(fontShadowColor); graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize)); } graphics.setColor(fontColor); graphics.drawString(text, x, y); }
From source file:com.aurel.track.report.gantt.data.TrackGanttRenderer.java
/** Prints the specified labelstring. If neccessary it reduces the * font size that the label fits in the specified space. * 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 ava2 s . com*/ private void drawLabel(String s, Graphics2D g2, int _x, int _y, Font f, boolean alignRight, int space) { 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 { while (g2.getFontMetrics().stringWidth(s) > space - 4) { log.debug("Reducing Font size for label " + s); f = new Font(f.getName(), f.getStyle(), f.getSize() - 1); g2.setFont(f); } x = _x + 2; } g2.drawString(s, x, _y); }
From source file:pt.lsts.neptus.plugins.sunfish.awareness.SituationAwareness.java
public void paintLabels(Graphics2D g, StateRenderer2D renderer) { g.setFont(new Font("Arial", Font.PLAIN, 11)); for (AssetTrack track : assets.values()) { AssetPosition p = track.getLatest(newestTimestampSelection); if (p == null || hiddenPosTypes.contains(p.getType())) continue; if (p.getTimestamp() < oldestTimestampSelection || p.getTimestamp() > newestTimestampSelection) continue; Point2D pt = renderer.getScreenPosition(p.getLoc()); g.setColor(track.getColor());/*from www . jav a2s . c o m*/ g.setColor(Color.black); String name = p.getAssetName();//assetProperties.containsKey(p.getAssetName()) ? assetProperties.get(p.getAssetName()).friendly : p.getAssetName(); g.drawString( name + " (" + DateTimeUtil.milliSecondsToFormatedString( System.currentTimeMillis() - p.getTimestamp()) + ")", (int) (pt.getX() + 13), (int) (pt.getY() + 5)); } }
From source file:com.newatlanta.bluedragon.CategoryAxis.java
public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {/* w w w . j a v a 2 s . c om*/ // create a new space object if one wasn't supplied... if (space == null) { space = new AxisSpace(); } // if the axis is not visible, no additional space is required... if (!isVisible()) { return space; } // calculate the max size of the tick labels (if visible)... double tickLabelHeight = 0.0; double tickLabelWidth = 0.0; if (isTickLabelsVisible()) { g2.setFont(getTickLabelFont()); AxisState state = new AxisState(); // we call refresh ticks just to get the maximum width or height if (RectangleEdge.isTopOrBottom(edge)) { // BEGIN fix for category labels that wrap // If space has been reserved to the left and right then we need to // reduce the plot area // by this amount so that the space needed by category labels that wrap // on to multiple lines // will be calculated properly. Rectangle2D newPlotArea = new Rectangle2D.Double(plotArea.getX(), plotArea.getY(), plotArea.getWidth() - space.getLeft() - space.getRight(), plotArea.getHeight()); refreshTicks(g2, state, newPlotArea, edge); // END fix for category labels that wrap } else { refreshTicks(g2, state, plotArea, edge); } if (edge == RectangleEdge.TOP) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.BOTTOM) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.LEFT) { tickLabelWidth = state.getMax(); } else if (edge == RectangleEdge.RIGHT) { tickLabelWidth = state.getMax(); } } // get the axis label size and update the space object... Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge); double labelHeight = 0.0; double labelWidth = 0.0; if (RectangleEdge.isTopOrBottom(edge)) { labelHeight = labelEnclosure.getHeight(); space.add(labelHeight + tickLabelHeight + this.getCategoryLabelPositionOffset(), edge); } else if (RectangleEdge.isLeftOrRight(edge)) { labelWidth = labelEnclosure.getWidth(); space.add(labelWidth + tickLabelWidth + this.getCategoryLabelPositionOffset(), edge); } return space; }
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 ww w . ja v a 2s .c om 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:org.squidy.designer.zoom.impl.SourceCodeShape.java
@Override protected void paintShapeZoomedIn(PPaintContext paintContext) { super.paintShapeZoomedIn(paintContext); Graphics2D g = paintContext.getGraphics(); PBounds bounds = getBoundsReference(); Class<?> type = nodeShape.getProcessable().getClass(); String typeName = type.getSimpleName(); g.setFont(fontName); g.drawString(typeName, (int) (bounds.x + 50), 140); g.setFont(fontSource);/*from ww w . j a v a 2s .com*/ // Calculate sourceName string if not done yet. // if (sourceName == null) { // sourceName = FontUtils.createCroppedLabelIfNecessary(g.getFontMetrics(), "Source: " // + sourceCodeURL.toString(), (int) (bounds.width)); // sourceNameX = (int) (bounds.x + bounds.width - FontUtils.getWidthOfText(g.getFontMetrics(), sourceName) - 20); // } // g.drawString(sourceName, sourceNameX, 90); // Calculate className string if not done yet. if (className == null) { className = FontUtils.createCroppedLabelIfNecessary(g.getFontMetrics(), "Class: " + type.getName(), (int) (bounds.width * 0.7)); classNameX = (int) (bounds.x + bounds.width - FontUtils.getWidthOfText(g.getFontMetrics(), className) - 20); } g.drawString(className, classNameX, 110); }
From source file:org.pentaho.reporting.engine.classic.core.layout.output.RenderUtility.java
public static DefaultImageReference createImageFromDrawable(final DrawableWrapper drawable, final StrictBounds rect, final StyleSheet box, final OutputProcessorMetaData metaData) { final int imageWidth = (int) StrictGeomUtility.toExternalValue(rect.getWidth()); final int imageHeight = (int) StrictGeomUtility.toExternalValue(rect.getHeight()); if (imageWidth == 0 || imageHeight == 0) { return null; }//from w w w . j a va 2s. co m final double scale = RenderUtility.getNormalizationScale(metaData); final Image image = ImageUtils.createTransparentImage((int) (imageWidth * scale), (int) (imageHeight * scale)); final Graphics2D g2 = (Graphics2D) image.getGraphics(); final Object attribute = box.getStyleProperty(ElementStyleKeys.ANTI_ALIASING); if (attribute != null) { if (Boolean.TRUE.equals(attribute)) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else if (Boolean.FALSE.equals(attribute)) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } } if (RenderUtility.isFontSmooth(box, metaData)) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } g2.scale(scale, scale); // the clipping bounds are a sub-area of the whole drawable // we only want to print a certain area ... final String fontName = (String) box.getStyleProperty(TextStyleKeys.FONT); final int fontSize = box.getIntStyleProperty(TextStyleKeys.FONTSIZE, 8); final boolean bold = box.getBooleanStyleProperty(TextStyleKeys.BOLD); final boolean italics = box.getBooleanStyleProperty(TextStyleKeys.ITALIC); if (bold && italics) { g2.setFont(new Font(fontName, Font.BOLD | Font.ITALIC, fontSize)); } else if (bold) { g2.setFont(new Font(fontName, Font.BOLD, fontSize)); } else if (italics) { g2.setFont(new Font(fontName, Font.ITALIC, fontSize)); } else { g2.setFont(new Font(fontName, Font.PLAIN, fontSize)); } g2.setStroke((Stroke) box.getStyleProperty(ElementStyleKeys.STROKE)); g2.setPaint((Paint) box.getStyleProperty(ElementStyleKeys.PAINT)); drawable.draw(g2, new Rectangle2D.Double(0, 0, imageWidth, imageHeight)); g2.dispose(); try { return new DefaultImageReference(image); } catch (final IOException e1) { logger.warn("Unable to fully load a given image. (It should not happen here.)", e1); return null; } }