List of usage examples for java.awt Graphics2D drawString
public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);
From source file:org.kuali.mobility.people.service.PeopleServiceImpl.java
@Override public BufferedImage generateObfuscatedImage(String text) { int width = 250; int height = 25; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); Font font = new Font("Arial", Font.PLAIN, 14); g2d.setFont(font);/*w w w .j a va 2 s.co m*/ RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); Paint bg = new Color(255, 255, 255); g2d.setPaint(bg); g2d.fillRect(0, 0, width, height); int x = 0; int y = height - 7; Paint textPaint = new Color(0, 0, 0); g2d.setPaint(textPaint); g2d.drawString(text, x, y); g2d.dispose(); return bufferedImage; }
From source file:main.MapKit.java
@Override public void paintWaypoint(Graphics2D g, JXMapViewer viewer, MyWaypoint w) { g = (Graphics2D) g.create();/*from www . j a v a2 s . c o m*/ Point2D point = viewer.getTileFactory().geoToPixel(w.getPosition(), viewer.getZoom()); int x = (int) point.getX(); int y = (int) point.getY(); if (w.amount == -1) { //means it's an original data point int fontSize = 28 - viewer.getZoom() * 2; //font size is larger when zoom in if (fontSize < 6) fontSize = 6; g.setFont(new Font("Arial", Font.PLAIN, fontSize)); g.setColor(w.color); g.drawString("x", x - fontSize / 2, y + fontSize / 2); g.dispose(); return; } if (origImage == null) { return; } BufferedImage myImg = map.get(w.color); if (myImg == null) { myImg = convert(origImage, w.color); map.put(w.color, myImg); } g.drawImage(myImg, x - myImg.getWidth() / 2, y - myImg.getHeight(), null); String label = String.valueOf(w.amount); // g.setFont(font); FontMetrics metrics = g.getFontMetrics(); int tw = metrics.stringWidth(label); int th = 1 + metrics.getAscent(); // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawString(label, x - tw / 2, y + th); g.dispose(); }
From source file:Main.java
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int cx = getSize().width / 2; int cy = getSize().height / 2; g2.translate(cx, cy);//from ww w.j ava2 s .co m g2.rotate(theta * Math.PI / 180); Shape oldClip = g2.getClip(); Shape e = new Ellipse2D.Float(-cx, -cy, cx * 2, cy * 2); g2.clip(e); Shape c = new Ellipse2D.Float(-cx, -cy, cx * 3 / 4, cy * 2); g2.setPaint(new GradientPaint(40, 40, Color.blue, 60, 50, Color.white, true)); g2.fill(c); g2.setPaint(Color.yellow); g2.fillOval(cx / 4, 0, cx, cy); g2.setClip(oldClip); g2.setFont(new Font("Times New Roman", Font.PLAIN, 64)); g2.setPaint(new GradientPaint(-cx, 0, Color.red, cx, 0, Color.black, false)); g2.drawString("Hello, 2D!", -cx * 3 / 4, cy / 4); AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) .75); g2.setComposite(ac); Shape r = new RoundRectangle2D.Float(0, -cy * 3 / 4, cx * 3 / 4, cy * 3 / 4, 20, 20); g2.setStroke(new BasicStroke(4)); g2.setPaint(Color.magenta); g2.fill(r); g2.setPaint(Color.green); g2.draw(r); g2.drawImage(image, -cx / 2, -cy / 2, this); }
From source file:com.stanley.captioner.Transcriber.java
public void start() { // Create stream speech recognizer. StreamSpeechRecognizer recognizer = null; try {/* w w w . j a v a2 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:FontShow.java
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Dialog", Font.PLAIN, 96); g2.setFont(font);//from w w w.j a va 2s .c o m int width = getSize().width; int height = getSize().height; String message = "Java2s"; FontRenderContext frc = g2.getFontRenderContext(); LineMetrics metrics = font.getLineMetrics(message, frc); float messageWidth = (float) font.getStringBounds(message, frc).getWidth(); // center text float ascent = metrics.getAscent(); float descent = metrics.getDescent(); float x = (width - messageWidth) / 2; float y = (height + metrics.getHeight()) / 2 - descent; int PAD = 25; g2.setPaint(getBackground()); g2.fillRect(0, 0, width, height); g2.setPaint(getForeground()); g2.drawString(message, x, y); g2.setPaint(Color.white); // Base lines drawLine(g2, x - PAD, y, x + messageWidth + PAD, y); drawLine(g2, x, y + PAD, x, y - ascent - PAD); g2.setPaint(Color.green); // Ascent line drawLine(g2, x - PAD, y - ascent, x + messageWidth + PAD, y - ascent); g2.setPaint(Color.red); // Descent line drawLine(g2, x - PAD, y + descent, x + messageWidth + PAD, y + descent); }
From source file:org.pentaho.platform.plugin.action.chartbeans.ChartAction.java
/** * Called to process the chart definition and data set to produce a usable chart. * * @throws ChartBootException/*from w w w.j a v a2 s. c om*/ * @throws ChartProcessingException * @throws ResourceException * @throws InvalidChartDefinition * @throws IOException * @throws PersistenceException * @see org.pentaho.platform.api.action.IAction#execute() */ public void execute() throws Exception { // // Runtime value validation is now part of the execute operation // validate(); if (bootException != null) { throw new ChartBootException(bootException); } // Transform IPentahoResultSet to an object array Object[][] data = processChartData(chartData, valueColumn); if (chartModel.getTheme() != null) { AbstractChartThemeFactory chartThemeFactory = new AbstractChartThemeFactory() { protected List<File> getThemeFiles() { ArrayList<File> themeFiles = new ArrayList<File>(); themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme1.xml"))); //$NON-NLS-1$ themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme2.xml"))); //$NON-NLS-1$ themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme3.xml"))); //$NON-NLS-1$ themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme4.xml"))); //$NON-NLS-1$ themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme5.xml"))); //$NON-NLS-1$ themeFiles.add(new File(PentahoSystem.getApplicationContext() .getSolutionPath("system/chartbeans/themes/Theme6.xml"))); //$NON-NLS-1$ return themeFiles; } }; if (!(chartModel.getPlot() instanceof DialPlot)) { Theme chartTheme = chartThemeFactory.getTheme(chartModel.getTheme()); if (chartTheme != null) { chartTheme.applyTo(chartModel); } } } // Make sure chart engine is loaded loadChartEngine(); // Set chart engine on chartModel for the ChartFactory to use chartModel.setChartEngineId(chartEngine); InputStream is = null; try { IChartLinkGenerator chartLinkGenerator = contentLinkingTemplate == null ? null : new ChartLinkGenerator(contentLinkingTemplate); is = ChartBeanFactory.createChart(data, scalingFactor, convertNullsToZero, valueColumn, seriesColumn, categoryColumn, chartModel, chartLinkGenerator, chartWidth, chartHeight, getOutputType()); // Wrap output as necessary if (OpenFlashChartPlugin.PLUGIN_ID.equals(chartEngine)) { // Convert stream to string, insert into HTML fragment and re-stream it StringBuilder sb = new StringBuilder(); int c = 0; // Build string while ((c = is.read()) >= 0) { sb.append((char) c); } IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); String contextPath = requestContext.getContextPath(); String flashContent = ChartBeansGeneratorUtil.mergeOpenFlashChartHtmlTemplate( sb.toString().replaceAll("\"", "\\\\\""), //$NON-NLS-1$ //$NON-NLS-2$ contextPath + "/" + this.getSwfPath() + "/" + getSwfName()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ is = new ByteArrayInputStream(flashContent.getBytes("utf-8")); //$NON-NLS-1$ } int val = 0; // TODO: Buffer for more efficiency while ((val = is.read()) != -1) { chartContentStream.write(val); } } catch (NoChartDataException ex) { if (JFreeChartPlugin.PLUGIN_ID.equals(chartEngine)) { BufferedImage image = new BufferedImage(chartWidth, chartHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setFont(new Font("serif", Font.BOLD, 14)); //$NON-NLS-1$ graphics.setColor(Color.BLACK); graphics.drawString("The chart data query returned no data.", 5, 5); //$NON-NLS-1$ String outputType = getMimeType(null).equals("image/jpg") ? "jpeg" : "png"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ImageIO.write(image, outputType, chartContentStream); } else { String flashContent = ChartBeansGeneratorUtil .buildEmptyOpenFlashChartHtmlFragment("The chart data query returned no data."); //$NON-NLS-1$ is = new ByteArrayInputStream(flashContent.getBytes("utf-8")); //$NON-NLS-1$ int val = 0; // TODO: Buffer for more efficiency while ((val = is.read()) != -1) { chartContentStream.write(val); } } } catch (ChartDataOverflowException ex) { if (JFreeChartPlugin.PLUGIN_ID.equals(chartEngine)) { BufferedImage image = new BufferedImage(chartWidth, chartHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setFont(new Font("serif", Font.BOLD, 14)); //$NON-NLS-1$ graphics.setColor(Color.BLACK); graphics.drawString(Messages.getInstance().getErrorString("ChartAction.TOO_MANY_DATA_POINTS"), 5, 5); //$NON-NLS-1$ graphics.drawString(Messages.getInstance().getErrorString("ChartAction.MAX_ALLOWED_DATA_POINTS", Integer.toString(ex.getMaxAllowedDataPoints())), 5, 25); //$NON-NLS-1$ String outputType = getMimeType(null).equals("image/jpg") ? "jpeg" : "png"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ImageIO.write(image, outputType, chartContentStream); } else { String flashContent = ChartBeansGeneratorUtil.buildEmptyOpenFlashChartHtmlFragment( Messages.getInstance().getErrorString("ChartAction.TOO_MANY_DATA_POINTS_HTML", //$NON-NLS-1$ Integer.toString(ex.getMaxAllowedDataPoints()))); is = new ByteArrayInputStream(flashContent.getBytes("utf-8")); //$NON-NLS-1$ int val = 0; // TODO: Buffer for more efficiency while ((val = is.read()) != -1) { chartContentStream.write(val); } } } }
From source file:org.squidy.designer.knowledgebase.RepositoryItem.java
@Override protected void paintShapeZoomedIn(PPaintContext paintContext) { super.paintShapeZoomedIn(paintContext); Graphics2D g = paintContext.getGraphics(); String information = "N/A"; if (information != null) { PBounds bounds = getBoundsReference(); double x = bounds.getX(); double width = bounds.getWidth(); String source = "Source: " + information; g.setFont(fontName);/*from w w w .j a va 2 s .c o m*/ g.drawString(getProcessableClass().getSimpleName(), (int) (x + 100), 80); g.setFont(fontSource); g.drawString(source, (int) (x + width - FontUtils.getWidthOfText(g.getFontMetrics(), source)) - 20, 130); } }
From source file:pl.edu.icm.visnow.lib.basic.viewers.Viewer2D.Display2DPanel.java
@Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; Font f = g2d.getFont();//from w w w . j a va 2 s. com Color c = g2d.getColor(); Rectangle clear = new Rectangle(0, 0, getWidth(), getHeight()); g2d.setPaint(bgColor); g2d.fill(clear); draw2D(g2d); g2d.setFont(titleFont); g2d.setColor(titleColor); g2d.drawString(titleText, 50, 10 + titleFont.getSize()); g2d.setFont(f); g2d.setColor(c); if (storingFrames && !dontWrite) { if (storingJPEG) { writeImage(controlsFrame.getMovieCreationPanel().getCurrentFrameFileName(), FORMAT_JPEG); } else { writeImage(controlsFrame.getMovieCreationPanel().getGenericFrameFileName(), FORMAT_PNG); } } }
From source file:com.alibaba.simpleimage.render.FootnoteDrawTextItem.java
@Override public void drawText(Graphics2D graphics, int width, int height) { if (StringUtils.isBlank(text) || StringUtils.isBlank(domainName)) { return;// w ww . jav a2 s . c o m } int x = 0, y = 0; int fontsize = ((int) (width * textWidthPercent)) / domainName.length(); if (fontsize < minFontSize) { return; } float fsize = (float) fontsize; Font font = domainFont.deriveFont(fsize); graphics.setFont(font); FontRenderContext context = graphics.getFontRenderContext(); int sw = (int) font.getStringBounds(domainName, context).getWidth(); x = width - sw - fontsize; y = height - fontsize; if (x <= 0 || y <= 0) { return; } if (fontShadowColor != null) { graphics.setColor(fontShadowColor); graphics.drawString(domainName, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize)); } graphics.setColor(fontColor); graphics.drawString(domainName, x, y); //draw company name fsize = (float) fontsize; font = defaultFont.deriveFont(fsize); graphics.setFont(font); context = graphics.getFontRenderContext(); sw = (int) font.getStringBounds(text, context).getWidth(); x = width - sw - fontsize; y = height - (int) (fontsize * 2.5); 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:savant.view.tracks.TrackRenderer.java
public void drawFeatureLabel(Graphics2D g2, String geneName, double startXPos, double y) { FontMetrics fm = g2.getFontMetrics(); double stringstartx = startXPos - fm.stringWidth(geneName) - 5; if (stringstartx <= 0) { Rectangle2D r = fm.getStringBounds(geneName, g2); int b = 2; Color textColor = g2.getColor(); g2.setColor(new Color(255, 255, 255, 200)); g2.fill(new RoundRectangle2D.Double(3.0, y - (fm.getHeight() - fm.getDescent()) - b, r.getWidth() + 2 * b, r.getHeight() + 2 * b, 8.0, 8.0)); g2.setColor(textColor);/*from ww w . j ava 2 s. com*/ g2.drawString(geneName, 5.0F, (float) y); } else { g2.drawString(geneName, (float) stringstartx, (float) y); } }