List of usage examples for java.awt Graphics2D drawString
public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
private byte[] createImage(int width, int height, String text) throws IOException { if (width < 0) { width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH; }/* ww w . j a v a 2s. c o m*/ if (height < 0) { height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT; } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) img.getGraphics(); g2.setBackground(new Color(220, 220, 220)); Dimension size; float fontSize = g2.getFont().getSize(); // Make the text as large as possible. do { g2.setFont(g2.getFont().deriveFont(fontSize)); FontMetrics metrics = g2.getFontMetrics(g2.getFont()); int hgt = metrics.getHeight(); int adv = metrics.stringWidth(text); size = new Dimension(adv + 2, hgt + 2); fontSize = fontSize + 1f; } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height)); g2.setColor(Color.DARK_GRAY); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2); g2.setColor(Color.LIGHT_GRAY); g2.drawRect(0, 0, width - 1, height - 1); ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height); ImageIO.write(img, "png", baos); baos.flush(); byte[] rawBytes = baos.toByteArray(); baos.close(); return rawBytes; }
From source file:com.us.servlet.AuthCode.java
protected void service(HttpServletRequest request, HttpServletResponse response) { final CodeAuth bean = AppHelper.CODE_AUTH; int width = NumberUtils.toInt(request.getParameter("width"), bean.getWidth()); int height = NumberUtils.toInt(request.getParameter("height"), bean.getHeight()); int x = width / (bean.getLength() + 1); int codeY = height - 4; int fontHeight = height - 2; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (StringUtil.hasText(request.getParameter("bgcolor"))) { graphics.setBackground(ColorHelper.hex2RGB(request.getParameter("bgcolor"))); }/* www .j av a2 s . c o m*/ graphics.fillRect(0, 0, width, height); graphics.setFont(new Font(bean.getFont(), Font.BOLD, fontHeight)); graphics.drawRect(0, 0, width - 1, height - 1); // if (bean.isBreakLine()) { for (int i = 0; i < 15; i++) { int x1 = RandomUtils.nextInt(width); int y1 = RandomUtils.nextInt(height); int x2 = RandomUtils.nextInt(12); int y2 = RandomUtils.nextInt(12); graphics.drawLine(x1, y1, x + x2, y1 + y2); } } char[] CHARSET_AREA = null; if (bean.getType().charAt(0) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS); } if (bean.getType().charAt(1) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER); } if (bean.getType().charAt(2) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < bean.getLength(); i++) { String rand = String.valueOf(CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)]); graphics.setColor(ColorHelper.color(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); graphics.drawString(rand, (i + 1) * x, codeY); randomCode.append(rand); } HttpSession session = request.getSession(); session.setAttribute(bean.getSessionKey(), randomCode.toString()); // ? response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/png"); try { // Servlet? ServletOutputStream sos = response.getOutputStream(); ImageIO.write(image, "png", sos); sos.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java
private Object prepareLegend(String legendKey, XMLAdapter jrxmlAdapter, List<OrderedDatasource<?>> datasources, String type, int resolution) throws ProcessletException { if ("net.sf.jasperreports.engine.JRRenderable".equals(type)) { return new LegendRenderable(datasources, resolution); } else {// w ww.ja v a 2 s . c o m OMElement legendRE = jrxmlAdapter.getElement(jrxmlAdapter.getRootElement(), new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{" + legendKey + "}']/jasper:reportElement", nsContext)); if (legendRE != null) { LOG.debug("Found legend with key '" + legendKey + "'."); int width = jrxmlAdapter.getRequiredNodeAsInteger(legendRE, new XPath("@width", nsContext)); int height = jrxmlAdapter.getRequiredNodeAsInteger(legendRE, new XPath("@height", nsContext)); width = adjustSpan(width, resolution); height = adjustSpan(height, resolution); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); // TODO: bgcolor? Color bg = Color.decode("0xFFFFFF"); g.setColor(bg); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); int k = 0; for (int i = 0; i < datasources.size(); i++) { if (k > height) { LOG.warn("The necessary legend size is larger than the available legend space."); } List<Pair<String, BufferedImage>> legends = datasources.get(i).getLegends(width); for (Pair<String, BufferedImage> legend : legends) { BufferedImage img = legend.second; if (img != null) { if (img.getWidth(null) < 50) { // it is assumed that no label is assigned g.drawImage(img, 0, k, null); g.drawString(legend.first, img.getWidth(null) + 10, k + img.getHeight(null) / 2); } else { g.drawImage(img, 0, k, null); } k = k + img.getHeight(null) + 10; } else { g.drawString("- " + legend.first, 0, k + 10); k = k + 20; } } } g.dispose(); return convertImageToReportFormat(type, bi); } } return null; }
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
@Override public void paint(Graphics2D g, StateRenderer2D renderer) { Point2D center = renderer.getScreenPosition(coords.squareCenter); double width = renderer.getZoom() * coords.cellWidth * coords.numCols; double height = renderer.getZoom() * coords.cellWidth * coords.numRows; g.setColor(new Color(0, 0, 255, 64)); g.translate(center.getX(), center.getY()); g.rotate(-renderer.getRotation());//from ww w.j a v a2s . co m g.fill(new Rectangle2D.Double(-width / 2, -height / 2, width, height)); g.rotate(renderer.getRotation()); g.translate(-center.getX(), -center.getY()); if (!active) return; g.setColor(Color.orange); int pos = 50; for (String v : nameTable.values()) { g.drawString(v + ": " + depths.get(v) + "m", 15, pos); pos += 20; } for (String vehicle : nameTable.values()) { LocationType src = positions.get(vehicle); LocationType dst = destinations.get(vehicle); if (!arrived.get(vehicle)) g.setColor(Color.red.darker()); else g.setColor(Color.green.darker()); float dash[] = { 4.0f }; g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f)); g.draw(new Line2D.Double(renderer.getScreenPosition(src), renderer.getScreenPosition(dst))); Point2D dstPt = renderer.getScreenPosition(dst); if (!arrived.get(vehicle)) g.setColor(Color.red.darker()); else g.setColor(Color.green.darker()); g.fill(new Ellipse2D.Double(dstPt.getX() - 4, dstPt.getY() - 4, 8, 8)); } }
From source file:org.fhcrc.cpl.viewer.quant.gui.PanelWithSpectrumChart.java
License:asdf
/** * * @param imageWidthEachScan//from w w w .j a va 2s .c o m * @param imageHeightEachScan * @param maxTotalImageHeight a hard boundary on the total image height. If imageHeightEachScan is too big, * given the total number of charts and this arg, it gets knocked down * @param outputFile * @throws java.io.IOException */ public void savePerScanSpectraImage(int imageWidthEachScan, int imageHeightEachScan, int maxTotalImageHeight, File outputFile) throws IOException { int numCharts = scanLineChartMap.size(); int widthPaddingForLabels = 50; imageHeightEachScan = Math.min(imageHeightEachScan, maxTotalImageHeight / numCharts); List<Integer> allScanNumbers = new ArrayList<Integer>(scanLineChartMap.keySet()); Collections.sort(allScanNumbers); List<PanelWithChart> allCharts = new ArrayList<PanelWithChart>(); for (int scanNumber : allScanNumbers) { PanelWithLineChart scanChart = scanLineChartMap.get(scanNumber); allCharts.add(scanChart); scanChart.setSize(imageWidthEachScan - widthPaddingForLabels, imageHeightEachScan); } BufferedImage perScanChartImage = MultiChartDisplayPanel.createImageForAllCharts(allCharts); BufferedImage perScanChartImageWithLabels = new BufferedImage(imageWidthEachScan, perScanChartImage.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = perScanChartImageWithLabels.createGraphics(); g.drawImage(perScanChartImage, widthPaddingForLabels, 0, null); g.setPaint(Color.WHITE); g.drawRect(0, 0, widthPaddingForLabels, perScanChartImage.getHeight()); for (int i = 0; i < allCharts.size(); i++) { int scanNumber = allScanNumbers.get(i); int chartTop = i * imageHeightEachScan; int chartMiddle = chartTop + (imageHeightEachScan / 2); if (lightFirstScanLine > 0 && lightLastScanLine > 0) { if (scanNumber >= lightFirstScanLine && scanNumber <= lightLastScanLine) g.setPaint(Color.GREEN); else g.setPaint(Color.RED); } else g.setPaint(Color.BLACK); g.drawString("" + scanNumber, 5, chartMiddle); } g.dispose(); ImageIO.write(perScanChartImageWithLabels, "png", outputFile); }
From source file:savant.view.tracks.BAMTrackRenderer.java
/** * Draw two read-shapes: one for forward and one for reverse. *///w w w . j av a2 s .co m private void drawStrandLegends(Graphics2D g2, int x, int y) { ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME); Shape pointyBar = getPointyBar(false, x, y - 12, 36.0, 12.0); g2.setColor(cs.getColor(ColourKey.FORWARD_STRAND)); g2.fill(pointyBar); g2.setColor(cs.getColor(ColourKey.INTERVAL_LINE)); g2.draw(pointyBar); pointyBar = getPointyBar(true, x, y - 12 + LEGEND_LINE_HEIGHT, 36.0, 12.0); g2.setColor(cs.getColor(ColourKey.REVERSE_STRAND)); g2.fill(pointyBar); g2.setColor(cs.getColor(ColourKey.INTERVAL_LINE)); g2.draw(pointyBar); g2.setColor(Color.BLACK); g2.setFont(LEGEND_FONT); g2.drawString(ColourKey.FORWARD_STRAND.getName(), x + 45, y); g2.drawString(ColourKey.REVERSE_STRAND.getName(), x + 45, y + LEGEND_LINE_HEIGHT); }
From source file:pl.edu.icm.visnow.system.main.VisNow.java
private static void renderSplashFrame(float progress, String loadText, String bottomTextUpperLine, String bottomTextLowerLine) { if (splash == null) { return;//from w ww . j a va 2 s.co m } try { Graphics2D g = splash.createGraphics(); if (g == null) { return; } if (!splash.isVisible()) return; Rectangle bounds = splash.getBounds(); Font f = g.getFont(); FontMetrics fm = g.getFontMetrics(f); java.awt.geom.Rectangle2D rect = fm.getStringBounds(loadText, g); int texth = (int) Math.ceil(rect.getHeight()); g.setComposite(AlphaComposite.Clear); //g.setColor(Color.RED); g.fillRect(PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN - texth - 5, bounds.width - PROGRESS_TEXT_X_POSITION, texth + 10); g.setFont(lowerLineFont); fm = g.getFontMetrics(g.getFont()); rect = fm.getStringBounds(bottomTextLowerLine, g); int lowerLineTextHeight = (int) Math.ceil(rect.getHeight()); g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN - lowerLineTextHeight - 5, bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10); g.setFont(f); fm = g.getFontMetrics(g.getFont()); rect = fm.getStringBounds(bottomTextUpperLine, g); texth = (int) Math.ceil(rect.getHeight()); g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN - texth - 5, bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10); g.setPaintMode(); // g.setColor(Color.BLACK); g.setColor(new Color(0, 75, 50)); g.drawString(loadText, PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN); g.drawString(bottomTextUpperLine, BOTTOM_TEXT_X_MARGIN, bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN); g.setFont(lowerLineFont); g.drawString(bottomTextLowerLine, BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN); g.setFont(f); // g.setColor(Color.BLACK); g.setColor(new Color(0, 150, 100)); g.drawRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT); int progressWidth = bounds.width - 2 * PROGRESS_BAR_X_MARGIN; int done = (int) (progressWidth * progress); g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, PROGRESS_BAR_X_MARGIN + done, PROGRESS_BAR_HEIGHT); if (progress >= 1.0f) { g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT); } splash.update(); } catch (IllegalStateException ex) { } }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
@Override public void paint(Graphics2D g2, StateRenderer2D renderer) { Graphics2D g = (Graphics2D) g2.create(); Point2D center = renderer.getScreenPosition(coords.squareCenter); double width = renderer.getZoom() * coords.cellWidth * coords.numCols; double height = renderer.getZoom() * coords.cellWidth * coords.numRows; g.setColor(new Color(0, 0, 255, 64)); g.translate(center.getX(), center.getY()); g.rotate(-renderer.getRotation());//from www .ja va 2 s .c o m g.fill(new Rectangle2D.Double(-width / 2, -height / 2, width, height)); g.rotate(renderer.getRotation()); g.translate(-center.getX(), -center.getY()); if (!active) { g.dispose(); return; } g.setColor(Color.orange); int pos = 50; for (String v : nameTable.values()) { g.drawString(v + ": " + depths.get(v) + "m", 15, pos); pos += 20; } for (String vehicle : nameTable.values()) { LocationType src = positions.get(vehicle); LocationType dst = destinations.get(vehicle); if (!arrived.get(vehicle)) g.setColor(Color.red.darker()); else g.setColor(Color.green.darker()); float dash[] = { 4.0f }; g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f)); g.draw(new Line2D.Double(renderer.getScreenPosition(src), renderer.getScreenPosition(dst))); Point2D dstPt = renderer.getScreenPosition(dst); if (!arrived.get(vehicle)) g.setColor(Color.red.darker()); else g.setColor(Color.green.darker()); g.fill(new Ellipse2D.Double(dstPt.getX() - 4, dstPt.getY() - 4, 8, 8)); } g.dispose(); }
From source file:components.SizeDisplayer.java
protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); //copy g Dimension minSize = getMinimumSize(); Dimension prefSize = getPreferredSize(); Dimension size = getSize();//ww w . j a va 2 s . c om int prefX = 0, prefY = 0; //Set hints so text looks nice. g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); //Draw the maximum size rectangle if we're opaque. if (isOpaque()) { g2d.setColor(getBackground()); g2d.fillRect(0, 0, size.width, size.height); } //Draw the icon. if (icon != null) { Composite oldComposite = g2d.getComposite(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); icon.paintIcon(this, g2d, (size.width - icon.getIconWidth()) / 2, (size.height - icon.getIconHeight()) / 2); g2d.setComposite(oldComposite); } //Draw the preferred size rectangle. prefX = (size.width - prefSize.width) / 2; prefY = (size.height - prefSize.height) / 2; g2d.setColor(Color.RED); g2d.drawRect(prefX, prefY, prefSize.width - 1, prefSize.height - 1); //Draw the minimum size rectangle. if (minSize.width != prefSize.width || minSize.height != prefSize.height) { int minX = (size.width - minSize.width) / 2; int minY = (size.height - minSize.height) / 2; g2d.setColor(Color.CYAN); g2d.drawRect(minX, minY, minSize.width - 1, minSize.height - 1); } //Draw the text. if (text != null) { Dimension textSize = getTextSize(g2d); g2d.setColor(getForeground()); g2d.drawString(text, (size.width - textSize.width) / 2, (size.height - textSize.height) / 2 + g2d.getFontMetrics().getAscent()); } g2d.dispose(); }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(M_sm.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);/*w w w . java2s. co m*/ FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }