List of usage examples for java.awt Graphics2D drawString
public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);
From source file:edu.ku.brc.ui.dnd.SimpleGlassPane.java
@Override protected void paintComponent(Graphics graphics) { Graphics2D g = (Graphics2D) graphics; Rectangle rect = getInternalBounds(); int width = rect.width; int height = rect.height; if (useBGImage) { // Create a translucent intermediate image in which we can perform // the soft clipping GraphicsConfiguration gc = g.getDeviceConfiguration(); if (img == null || img.getWidth() != width || img.getHeight() != height) { img = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); }/*from w w w. ja va2 s .c o m*/ Graphics2D g2 = img.createGraphics(); // Clear the image so all pixels have zero alpha g2.setComposite(AlphaComposite.Clear); g2.fillRect(0, 0, width, height); g2.setComposite(AlphaComposite.Src); g2.setColor(new Color(0, 0, 0, 85)); g2.fillRect(0, 0, width, height); if (delegateRenderer != null) { delegateRenderer.render(g, g2, img); } g2.dispose(); // Copy our intermediate image to the screen g.drawImage(img, rect.x, rect.y, null); } super.paintComponent(graphics); if (StringUtils.isNotEmpty(text)) { Graphics2D g2 = (Graphics2D) graphics; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(fillColor); g2.fillRect(margin.left, margin.top, rect.width, rect.height); g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize)); FontMetrics fm = g2.getFontMetrics(); int tw = fm.stringWidth(text); int th = fm.getHeight(); int tx = (rect.width - tw) / 2; int ty = (rect.height - th) / 2; if (yPos != null) { ty = yPos; } int expand = 20; int arc = expand * 2; g2.setColor(new Color(0, 0, 0, 50)); int x = margin.left + tx - (expand / 2); int y = margin.top + ty - fm.getAscent() - (expand / 2); drawBGContainer(g2, true, x + 4, y + 6, tw + expand, th + expand, arc, arc); g2.setColor(new Color(255, 255, 255, 220)); drawBGContainer(g2, true, x, y, tw + expand, th + expand, arc, arc); g2.setColor(Color.DARK_GRAY); drawBGContainer(g2, false, x, y, tw + expand, th + expand, arc, arc); g2.setColor(textColor == null ? Color.BLACK : textColor); g2.drawString(text, tx, ty); } }
From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java
/** * Renders this image/* w ww .ja v a2s . c o m*/ * * @return The image data */ private final byte[] render() throws IOException { Graphics2D gfx = (Graphics2D) this.image.getGraphics(); if (config.isFontAntialiasing()) gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int curWidth = config.getTextMarginLeft(); FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false); for (int i = 0; i < charAttsList.size(); i++) { CharAttributes cf = (CharAttributes) charAttsList.get(i); TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext()); AffineTransform textAt = new AffineTransform(); textAt.translate(curWidth, this.height - cf.getRise()); if (cf.getRotation() != 0) { textAt.rotate(cf.getRotation()); } if (cf.getShearX() > 0.0) textAt.shear(cf.getShearX(), cf.getShearY()); Shape shape = text.getOutline(textAt); curWidth += shape.getBounds().getWidth() + config.getTextSpacing(); if (config.isUseImageBackground()) gfx.setColor(Color.BLACK); else gfx.setXORMode(Color.BLACK); gfx.fill(shape); } if (config.isEffectsNoise()) { noiseEffects(gfx, image); } if (config.isUseTimestamp()) { if (config.isEffectsNoise()) gfx.setColor(Color.WHITE); else gfx.setColor(Color.BLACK); TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ()); Calendar cal = new GregorianCalendar(tz); SimpleDateFormat formatter; if (config.isUseTimestamp24hr()) formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); else formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z"); formatter.setTimeZone(tz); Font font = gfx.getFont(); Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize()); gfx.setFont(newFont); gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1); } return toImageData(image); }
From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java
private void prepareScaleBar(Map<String, Object> params, String scalebarKey, XMLAdapter jrxmlAdapter, List<OrderedDatasource<?>> datasources, String type, Envelope bbox, double mapWidth) throws ProcessletException { OMElement sbRep = jrxmlAdapter.getElement(jrxmlAdapter.getRootElement(), new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{" + scalebarKey + "}']/jasper:reportElement", nsContext));//from w w w .java 2 s .c o m if (sbRep != null) { // TODO: rework this! LOG.debug("Found scalebar with key '" + scalebarKey + "'."); int w = jrxmlAdapter.getRequiredNodeAsInteger(sbRep, new XPath("@width", nsContext)); int h = jrxmlAdapter.getRequiredNodeAsInteger(sbRep, new XPath("@height", nsContext)); BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); String fontName = null; int fontSize = 8; int desiredWidth = w - 30; // calculate scale bar max scale and size int length = 0; double lx = 0; double scale = 0; for (int i = 0; i < 100; i++) { double k = 0; double dec = 30 * Math.pow(10, i); for (int j = 0; j < 9; j++) { k += dec; double tx = -k * (mapWidth / bbox.getSpan0()); if (Math.abs(tx - lx) < desiredWidth) { length = (int) Math.round(Math.abs(tx - lx)); scale = k; } else { break; } } } // draw scale bar base line g.setStroke(new BasicStroke((desiredWidth + 30) / 250)); g.setColor(Color.black); g.drawLine(10, 30, length + 10, 30); double dx = length / 3d; double vdx = scale / 3; double div = 1; String uom = "m"; if (scale > 1000) { div = 1000; uom = "km"; } // draw scale bar scales if (fontName == null) { fontName = "SANS SERIF"; } g.setFont(new Font(fontName, Font.PLAIN, fontSize)); DecimalFormat df = new DecimalFormat("##.# "); DecimalFormat dfWithUom = new DecimalFormat("##.# " + uom); for (int i = 0; i < 4; i++) { String label = i < 3 ? df.format((vdx * i) / div) : dfWithUom.format((vdx * i) / div); g.drawString(label, (int) Math.round(10 + i * dx) - 8, 10); g.drawLine((int) Math.round(10 + i * dx), 30, (int) Math.round(10 + i * dx), 20); } for (int i = 0; i < 7; i++) { g.drawLine((int) Math.round(10 + i * dx / 2d), 30, (int) Math.round(10 + i * dx / 2d), 25); } g.dispose(); params.put(scalebarKey, convertImageToReportFormat(type, img)); LOG.debug("added scalebar"); } }
From source file:org.fhcrc.cpl.viewer.quant.gui.QuantitationVisualizer.java
/** * Save chart to an image file, with or without the sidebar information and/or theoretical peaks * @param chartPanel/*w w w.j a va 2s. c om*/ * @param outFile * @param sidebarWidth * @param charge * @param lightMz * @param heavyMz * @param ratio * @throws IOException */ public void saveChartToImageFile(PanelWithChart chartPanel, File outFile, int sidebarWidth, int charge, float lightMz, float heavyMz, float ratio, boolean writeChartInfo, int width, int height, boolean overrideSize) throws IOException { BufferedImage spectrumImage = null; if (overrideSize) spectrumImage = chartPanel.createImage(width, height); else spectrumImage = chartPanel.createImage(); BufferedImage imageToWrite = spectrumImage; if (writeChartInfo) { int fullImageWidth = spectrumImage.getWidth() + sidebarWidth; imageToWrite = new BufferedImage(fullImageWidth, spectrumImage.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = imageToWrite.createGraphics(); g.drawImage(spectrumImage, sidebarWidth, 0, null); //write in sidebar int lineHeight = 20; int lineNum = 1; int indent = 5; if (writeChartInfo) { g.setPaint(Color.WHITE); // g.drawString(peptide, indent, lineNum++ * lineHeight); // g.drawString("Charge=" + charge, indent, lineNum++ * lineHeight); // g.drawString("Light mass=" + lightMass, indent, lineNum++ * lineHeight); // g.drawString("Light m/z=" + lightMz, indent, lineNum++ * lineHeight); // g.drawString("Heavy m/z=" + heavyMz, indent, lineNum++ * lineHeight); // g.drawString("Light int=" + lightIntensity, indent, lineNum++ * lineHeight); // g.drawString("Heavy int=" + heavyIntensity, indent, lineNum++ * lineHeight); g.drawString("Ratio=" + ratio, indent, lineNum++ * lineHeight); // g.drawString("MinscanLt=" + lightMinQuantScan, indent, lineNum++ * lineHeight); // g.drawString("MaxscanLt=" + lightMaxQuantScan, indent, lineNum++ * lineHeight); // g.drawString("MinScanHv=" + heavyMinQuantScan, indent, lineNum++ * lineHeight); // g.drawString("MaxScanHv=" + heavyMaxQuantScan, indent, lineNum++ * lineHeight); // g.drawString("ID scan=" + idScan, indent, lineNum++ * lineHeight); // g.drawString("IDscan level=" + idScanLevel, indent, lineNum++ * lineHeight); //theoretical peaks in bottom left int theoreticalPeaksHeight = (int) (sidebarWidth * 2.0 / 3.0); int theoreticalPeaksTop = spectrumImage.getHeight() - theoreticalPeaksHeight - 10; g.drawString("Ideal Peaks", indent, theoreticalPeaksTop - 20); //combined theoretical peak distribution chart PanelWithPeakChart theoreticalPeakChart = buildTheoreticalPeakChart(lightMz, heavyMz, charge, ratio, sidebarWidth, (int) (sidebarWidth * 2.0 / 3.0)); g.drawImage(theoreticalPeakChart.createImage(sidebarWidth, (int) (sidebarWidth * 2.0 / 3.0)), 0, theoreticalPeaksTop, null); } g.dispose(); } ImageIO.write(imageToWrite, "png", outFile); }
From source file:org.gumtree.vis.hist2d.Hist2DPanel.java
@Override protected void drawToolTipFollower(Graphics2D g2, int x, int y) { Rectangle2D dataArea = getScreenDataArea(); if (((int) dataArea.getMinX() < x) && (x < (int) dataArea.getMaxX()) && ((int) dataArea.getMinY() < y) && (y < (int) dataArea.getMaxY())) { String text = String.format("(%." + mouseFollowerXPrecision + "f, %." + mouseFollowerYPrecision + "f, %." + mouseFollowerZPrecision + "f)", getChartX(), getChartY(), getChartZ()); int xLoc = x + 10; int yLoc = y + 20; double width = text.length() * 5.5; double height = 15; if (xLoc + width > dataArea.getMaxX()) { xLoc = (int) (x - width); }//from w w w .j a va2 s .com if (yLoc + height > dataArea.getMaxY()) { yLoc = (int) (y - height); } Rectangle2D toolTipArea = new Rectangle2D.Double(xLoc, yLoc, width, height); g2.setColor(Color.white); g2.fill(toolTipArea); g2.setColor(Color.black); g2.drawString(text, xLoc + 3, yLoc + 11); } }
From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java
private void renderRange(LongRange pRange, LongRange pStartRange, LongRange pArriveRange, boolean pIsStartRange, boolean pIsArriveRange, Graphics2D pG2D, TimeSpan pSpanForRange, HashMap<String, Object> pPopupInfo) { int rangeStart = 0; int rangeWidth = 0; if (pRange.overlapsRange(pStartRange)) { //start range rendering long startDelta = pStartRange.getMinimumLong(); rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); // int rangeEnd = Math.round((pRange.getMaximumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); rangeWidth = Math// w w w . ja v a 2 s. c o m .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); } else if (pRange.overlapsRange(pArriveRange)) { //end range rendering long startDelta = pStartRange.getMinimumLong(); rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); // int rangeEnd = Math.round((pRange.getMaximumLong() - arriveDelta) / DateUtils.MILLIS_PER_MINUTE); rangeWidth = Math .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); } //correct small widths if (rangeWidth == 0) { rangeWidth = 5; } long max = Math.round( (pArriveRange.getMaximumLong() - pStartRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); if (rangeStart > max) { return; } SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); String labelString = ""; if (pSpanForRange != null) { labelString = pSpanForRange.toString(); } else { labelString = f.format(new Date(pRange.getMinimumLong())) + " bis " + f.format(new Date(pRange.getMaximumLong())); } Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(labelString, pG2D); if (pIsStartRange) { pG2D.setColor(Color.RED); pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.RED); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f)); pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight()); } else if (pIsArriveRange) { pG2D.setColor(Color.GREEN.darker()); pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.GREEN.darker()); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f)); pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight() + 40); } else { pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); Point loc = getMousePosition(); if (loc != null && new Rectangle(rangeStart, 20, rangeWidth, 20).contains(loc)) { pPopupInfo.put("popup.location", loc); pPopupInfo.put("popup.label", labelString); pPopupInfo.put("active.range", pRange); pPopupInfo.put("span.for.range", pSpanForRange); } } }
From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java
/** * Draws the label for one axis./*from w w w . j a va 2 s .c om*/ * * @param g2 the graphics device. * @param plotArea the plot area * @param value the value of the label (ignored). * @param cat the category (zero-based index). * @param startAngle the starting angle. * @param extent the extent of the arc. */ protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle, double extent) { FontRenderContext frc = g2.getFontRenderContext(); String label = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { // if series are in rows, then the categories are the column keys label = this.labelGenerator.generateColumnLabel(this.dataset, cat); } else { // if series are in columns, then the categories are the row keys label = this.labelGenerator.generateRowLabel(this.dataset, cat); } Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); LineMetrics lm = getLabelFont().getLineMetrics(label, frc); double ascent = lm.getAscent(); Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle); Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY()); g2.setComposite(saveComposite); }
From source file:edu.ku.brc.ui.UIRegistry.java
/** * Writes a string message into the BufferedImage on GlassPane and sets the main component's visibility to false and * shows the GlassPane./*from www. ja v a 2s . c o m*/ * @param msg the message * @param pointSize the Font point size for the message to be writen in */ public static GhostGlassPane writeGlassPaneMsg(final String msg, final int pointSize) { GhostGlassPane glassPane = getGlassPane(); if (glassPane != null) { glassPane.finishDnD(); } glassPane.setMaskingEvents(true); Component mainComp = get(MAINPANE); if (mainComp != null && glassPane != null) { JFrame frame = (JFrame) get(FRAME); frameRect = frame.getBounds(); int y = 0; JMenuBar menuBar = null; Dimension size = mainComp.getSize(); if (UIHelper.getOSType() != UIHelper.OSTYPE.MacOSX) { menuBar = frame.getJMenuBar(); size.height += menuBar.getSize().height; y += menuBar.getSize().height; } BufferedImage buffer = getGlassPaneBufferedImage(size.width, size.height); Graphics2D g2 = buffer.createGraphics(); if (menuBar != null) { menuBar.paint(g2); } g2.translate(0, y); mainComp.paint(g2); g2.translate(0, -y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(new Color(255, 255, 255, 128)); g2.fillRect(0, 0, size.width, size.height); g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize)); FontMetrics fm = g2.getFontMetrics(); int tw = fm.stringWidth(msg); int th = fm.getHeight(); int tx = (size.width - tw) / 2; int ty = (size.height - th) / 2; int expand = 20; int arc = expand * 2; g2.setColor(Color.WHITE); g2.fillRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc, arc); g2.setColor(Color.DARK_GRAY); g2.drawRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc, arc); g2.setColor(Color.BLACK); g2.drawString(msg, tx, ty); g2.dispose(); glassPane.setImage(buffer); glassPane.setPoint(new Point(0, 0), GhostGlassPane.ImagePaintMode.ABSOLUTE); glassPane.setOffset(new Point(0, 0)); glassPane.setVisible(true); mainComp.setVisible(false); //Using paintImmediately fixes problems with glass pane not showing, such as for workbench saves initialed //during workbench or app shutdown. Don't know if there is a better way to fix it. //glassPane.repaint(); glassPane.paintImmediately(glassPane.getBounds()); showingGlassPane = true; } return glassPane; }
From source file:savant.view.swing.GraphPane.java
/** * Render the background of this GraphPane * * @param g The graphics object to use//from w w w.j ava 2 s .c o m */ private void renderBackground(Graphics2D g2, boolean xGridOn, boolean yGridOn) { int h = getHeight(); int w = getWidth(); // Paint a gradient from top to bottom GradientPaint gp0 = new GradientPaint(0, 0, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_TOP), 0, h, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_BOTTOM)); g2.setPaint(gp0); g2.fillRect(0, 0, w, h); // We don't want the axes stomping on our labels, so make sure the clip excludes them. Area clipArea = new Area(new Rectangle(0, 0, w, h)); Color gridColor = ColourSettings.getColor(ColourKey.AXIS_GRID); if (yGridOn) { // Smallish font for tick labels. Font tickFont = g2.getFont().deriveFont(Font.PLAIN, 9); int[] yTicks = MiscUtils.getTickPositions(transformYPixel(getHeight()), transformYPixel(0.0)); g2.setColor(gridColor); g2.setFont(tickFont); for (int t : yTicks) { double y = transformYPos(t); // Skip labels at the top or bottom of the window because they look stupid. if (y != 0.0 && y != getHeight()) { String s = Integer.toString(t); Rectangle2D labelRect = tickFont.getStringBounds(s, g2.getFontRenderContext()); double baseline = y + labelRect.getHeight() * 0.5 - 2.0; g2.drawString(s, 4.0F, (float) baseline); clipArea.subtract(new Area(new Rectangle2D.Double(3.0, baseline - labelRect.getHeight() - 1.0, labelRect.getWidth() + 2.0, labelRect.getHeight() + 2.0))); } } g2.setClip(clipArea); for (int t2 : yTicks) { double y = transformYPos(t2); g2.draw(new Line2D.Double(0.0, y, w, y)); } } if (xGridOn) { Range r = LocationController.getInstance().getRange(); int[] xTicks = MiscUtils.getTickPositions(r); g2.setColor(gridColor); for (int t : xTicks) { double x = transformXPos(t); g2.draw(new Line2D.Double(x, 0, x, h)); } } g2.setClip(null); }
From source file:com.moviejukebox.plugin.DefaultImagePlugin.java
private BufferedImage drawText(BufferedImage bi, String outputText, boolean verticalAlign) { Graphics2D g2d = bi.createGraphics(); g2d.setFont(new Font(textFont, Font.BOLD, textFontSize)); FontMetrics fm = g2d.getFontMetrics(); int textWidth = fm.stringWidth(outputText); int imageWidth = bi.getWidth(); int imageHeight = bi.getHeight(); int leftAlignment; int topAlignment; if (textAlignment.equalsIgnoreCase(LEFT)) { leftAlignment = textOffset;/* ww w .j ava2s.c om*/ } else if (textAlignment.equalsIgnoreCase(RIGHT)) { leftAlignment = imageWidth - textWidth - textOffset; } else { leftAlignment = (imageWidth / 2) - (textWidth / 2); } if (verticalAlign) { // Align the text to the top topAlignment = fm.getHeight() - 10; } else { // Align the text to the bottom topAlignment = imageHeight - 10; } // Create the drop shadow if (StringUtils.isNotBlank(textFontShadow)) { g2d.setColor(getColor(textFontShadow, Color.DARK_GRAY)); g2d.drawString(outputText, leftAlignment + 2, topAlignment + 2); } // Create the text itself g2d.setColor(getColor(textFontColor, Color.LIGHT_GRAY)); g2d.drawString(outputText, leftAlignment, topAlignment); g2d.dispose(); return bi; }