List of usage examples for java.awt Graphics2D getFontMetrics
public FontMetrics getFontMetrics()
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. *///from www .ja va 2 s.c o m 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:ucar.unidata.idv.control.chart.TrackSegment.java
/** * Draws the wayPoint./* ww w. j av a 2 s. c o m*/ * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param rendererIndex the renderer index. * @param info an optional info object that will be populated with * entity information. */ public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) { super.setGraphicsState(g2); if (!getPlotWrapper().okToDraw(this)) { return; } WayPoint leftWayPoint = getLeft(); WayPoint rightWayPoint = getRight(); g2.setStroke(new BasicStroke()); int x1 = leftWayPoint.getXFromValue(dataArea, domainAxis); int x2 = rightWayPoint.getXFromValue(dataArea, domainAxis); int top = (int) (dataArea.getY()); int bottom = (int) (dataArea.getY() + dataArea.getHeight()); FontMetrics fm = g2.getFontMetrics(); int width = fm.stringWidth(getName()); int height = fm.getAscent() + fm.getDescent(); if (getSelected()) { g2.setColor(Color.red); } else { g2.setColor(Color.black); } // int y = bottom-3; y = top - 2; int textLeft = x1 + (x2 - x1) / 2 - width / 2; g2.drawString(getName(), textLeft, y); g2.setStroke(new BasicStroke(2.0f)); g2.drawLine(x1, top + 1, x2, top + 1); g2.setStroke(new BasicStroke(1.0f)); g2.setColor(Color.gray); g2.drawLine(x1, top, x1, bottom - WayPoint.ANNOTATION_WIDTH); g2.drawLine(x2, top, x2, bottom - WayPoint.ANNOTATION_WIDTH); }
From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java
public static boolean calculateElementSizes(final Graphics2D gfx, final MindMap model, final MindMapPanelConfig cfg) { boolean result = false; final Topic root = model == null ? null : model.getRoot(); if (root != null) { if (gfx.getFontMetrics() != null) { model.resetPayload();/*from w w w.ja v a 2s . c om*/ setElementSizesForElementAndChildren(gfx, cfg, root, 0); result = true; } else { root.setPayload(null); } } return result; }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
public void drawString(Graphics g, String text, RectangularShape bounds, Align align, double angle, boolean multiline) { Graphics2D g2 = (Graphics2D) g; Font font = g2.getFont();/*from w w w . j a v a2 s .c o m*/ if (angle != 0) { g2.setFont(font.deriveFont(AffineTransform.getRotateInstance(Math.toRadians(angle)))); } Rectangle2D sSize = g2.getFontMetrics().getStringBounds(text, g2); Point2D pos = getPoint(bounds, align); double x = pos.getX(); double y = pos.getY() + sSize.getHeight(); switch (align) { case TopCenter: case BottomCenter: case Center: x -= (sSize.getWidth() / 2); break; case TopRight: case MiddleRight: case BottomRight: x -= (sSize.getWidth()); break; case BottomLeft: case MiddleLeft: case TopLeft: break; } if (multiline) { // Create a new LineBreakMeasurer from the paragraph. // It will be cached and re-used. //if (lineMeasurer == null) { AttributedCharacterIterator paragraph = new AttributedString(text).getIterator(); paragraphStart = paragraph.getBeginIndex(); paragraphEnd = paragraph.getEndIndex(); FontRenderContext frc = g2.getFontRenderContext(); lineMeasurer = new LineBreakMeasurer(paragraph, frc); //} // Set break width to width of Component. float breakWidth = (float) bounds.getWidth(); float drawPosY = (float) y; // Set position to the index of the first character in the paragraph. lineMeasurer.setPosition(paragraphStart); // Get lines until the entire paragraph has been displayed. while (lineMeasurer.getPosition() < paragraphEnd) { // Retrieve next layout. A cleverer program would also cache // these layouts until the component is re-sized. TextLayout layout = lineMeasurer.nextLayout(breakWidth); // Compute pen x position. If the paragraph is right-to-left we // will align the TextLayouts to the right edge of the panel. // Note: this won't occur for the English text in this sample. // Note: drawPosX is always where the LEFT of the text is placed. float drawPosX = layout.isLeftToRight() ? (float) x : (float) x + breakWidth - layout.getAdvance(); // Move y-coordinate by the ascent of the layout. drawPosY += layout.getAscent(); // Draw the TextLayout at (drawPosX, drawPosY). layout.draw(g2, drawPosX, drawPosY); // Move y-coordinate in preparation for next layout. drawPosY += layout.getDescent() + layout.getLeading(); } } else { g2.drawString(text, (float) x, (float) y); } g2.setFont(font); }
From source file:org.csml.tommo.sugar.modules.MappingQuality.java
protected void drawRowHeader(Graphics2D g2, final MappingQualityTableModel model, int imgSize, int width, int xOffset) { for (int r = 0; r < model.getRowCount(); r++) { int i = r / model.getTileNumeration().getCycleSize(); String s = i < MappingQualityMatrix.THRESHOLDS.length ? "MAPQ<" + MappingQualityMatrix.THRESHOLDS[i] : "AVERAGE"; if (model.getCycleID(r) == 0) { int stringHeight = g2.getFont().getSize(); //g2.getFontMetrics().getHeight(); int stringWidth = g2.getFontMetrics().stringWidth(s); g2.drawString(s, 1 + width + (xOffset - 1 - stringWidth) / 2, imgSize * (r + 1) - (imgSize - stringHeight) / 2); }//from www . j a va2 s. c o m } }
From source file:org.tinymediamanager.ui.components.ImageLabel.java
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (scaledImage != null) { int originalWidth = scaledImage.getWidth(null); int originalHeight = scaledImage.getHeight(null); // calculate new height/width int newWidth = 0; int newHeight = 0; int offsetX = 0; int offsetY = 0; if (drawBorder && !drawFullWidth) { Point size = ImageCache.calculateSize(this.getWidth() - 8, this.getHeight() - 8, originalWidth, originalHeight, true); // calculate offsets if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) { offsetX = this.getWidth() - size.x - 8; }/* w w w . j a v a 2s . c o m*/ if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) { offsetY = this.getHeight() - size.y - 8; } if (position == Position.CENTER) { offsetX = (this.getWidth() - size.x - 8) / 2; offsetY = (this.getHeight() - size.y - 8) / 2; } newWidth = size.x; newHeight = size.y; // when the image size differs too much - reload and rescale the original image recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight); g.setColor(Color.BLACK); g.drawRect(offsetX, offsetY, size.x + 7, size.y + 7); g.setColor(Color.WHITE); g.fillRect(offsetX + 1, offsetY + 1, size.x + 6, size.y + 6); // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX + 4, offsetY + 4, newWidth, newHeight, this); g.drawImage(scaledImage, offsetX + 4, offsetY + 4, newWidth, newHeight, this); } else { Point size = null; if (drawFullWidth) { size = new Point(this.getWidth(), this.getWidth() * originalHeight / originalWidth); } else { size = ImageCache.calculateSize(this.getWidth(), this.getHeight(), originalWidth, originalHeight, true); } // calculate offsets if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) { offsetX = this.getWidth() - size.x; } if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) { offsetY = this.getHeight() - size.y; } if (position == Position.CENTER) { offsetX = (this.getWidth() - size.x) / 2; offsetY = (this.getHeight() - size.y) / 2; } newWidth = size.x; newHeight = size.y; // when the image size differs too much - reload and rescale the original image recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight); // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX, offsetY, newWidth, newHeight, this); g.drawImage(scaledImage, offsetX, offsetY, newWidth, newHeight, this); } } else { // draw border and background if (drawBorder) { g.setColor(Color.BLACK); g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1); if (getParent().isOpaque()) { g.setColor(getParent().getBackground()); g.fillRect(1, 1, this.getWidth() - 2, this.getHeight() - 2); } } // calculate diagonal int diagonalSize = (int) Math .sqrt(this.getWidth() * this.getWidth() + this.getHeight() * this.getHeight()); // draw text String text = ""; if (alternativeText != null) { text = alternativeText; } else { text = BUNDLE.getString("image.nonefound"); //$NON-NLS-1$ } if (!getParent().isOpaque()) { text = ""; } Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); AffineTransform orig = g2.getTransform(); AffineTransform at = new AffineTransform(orig); at.translate(0, this.getHeight()); at.rotate(this.getWidth(), -this.getHeight()); g2.setTransform(at); g2.setColor(Color.BLACK); g2.setFont(FONT); FontMetrics fm = g2.getFontMetrics(); int x = (diagonalSize - fm.stringWidth(text)) / 2; int y = (fm.getAscent() - fm.getDescent()) / 2; g2.drawString(text, x, y); // g2.drawLine(0, 0, diagonalSize, 0); at.translate(0, -this.getHeight()); g2.setTransform(orig); } }
From source file:edu.kit.dama.ui.components.TextImage.java
/** * Get the bytes of the final image./*w w w .java 2 s. c o m*/ * * @return The byte array containing the bytes of the resulting image. * * @throws IOException if creating the image fails. */ public byte[] getBytes() throws IOException { Image transparentImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource( new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB).getSource(), new RGBImageFilter() { @Override public final int filterRGB(int x, int y, int rgb) { return (rgb << 8) & 0xFF000000; } })); //create the actual image and overlay it by the transparent background BufferedImage outputImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = outputImage.createGraphics(); g2d.drawImage(transparentImage, 0, 0, null); //draw the remaining stuff g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setColor(color); g2d.fillRoundRect(0, 0, size, size, 20, 20); g2d.setColor(new Color(Math.round((float) color.getRed() * .9f), Math.round((float) color.getGreen() * .9f), Math.round((float) color.getBlue() * .9f))); g2d.drawRoundRect(0, 0, size - 1, size - 1, 20, 20); Font font = new Font("Dialog", Font.BOLD, size - 4); g2d.setFont(font); g2d.setColor(Color.WHITE); String s = text.toUpperCase().substring(0, 1); FontMetrics fm = g2d.getFontMetrics(); float x = ((float) size - (float) fm.stringWidth(s)) / 2f; float y = ((float) fm.getAscent() + (float) ((float) size - ((float) fm.getAscent() + (float) fm.getDescent())) / 2f) - 1f; g2d.drawString(s, x, y); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ImageIO.write(outputImage, "png", bout); g2d.dispose(); return bout.toByteArray(); }
From source file:org.squidy.designer.util.DrawableString.java
/** * @param g/*from ww w. j av a 2 s . c o m*/ */ private void update(Graphics2D g, double viewScale) { Cache.Item item; // use screen if no bounds set if (bounds == null) { bounds = g.getDeviceConfiguration().getBounds(); } // get item extents from cache or calculate if (cache == null || dirty) { cache = new Cache(); item = null; } else { item = cache.get(viewScale); } if (item != null) { drawValue = item.drawValue; positionX = item.positionX; } else { FontMetrics fm; int width, height; // font width does not scale linear to view scale fm = g.getFontMetrics(); drawValue = FontUtils.createCroppedLabelIfNecessary(fm, value, bounds.width - 50); positionX = bounds.x; if (alignmentH == AlignmentH.CENTER) { width = FontUtils.getWidthOfText(fm, drawValue); positionX += (bounds.width - width) / 2; } else if (alignmentH == AlignmentH.RIGHT) { width = FontUtils.getWidthOfText(fm, drawValue); positionX += (bounds.width - width); } // font height keeps the same all the time if (dirty) { positionY = bounds.y; if (alignmentV == AlignmentV.CENTER) { height = (int) fm.getLineMetrics(drawValue, g).getHeight(); positionY += (bounds.height - height) / 2; } else if (alignmentV == AlignmentV.BOTTOM) { height = (int) fm.getLineMetrics(drawValue, g).getHeight(); positionY += (bounds.height - height); } } // store extents in cache cache.put(drawValue, positionX, viewScale); } dirty = false; }
From source file:ca.sqlpower.wabit.report.ChartRenderer.java
public boolean renderReportContent(Graphics2D g, double width, double height, double scaleFactor, int pageIndex, boolean printing, SPVariableResolver variablesContext) { if (printing) { // If we're printing a streaming query, we have to // print whatever's displayed. if (this.chartCache == null || (this.chartCache != null && !this.chartCache.getQuery().isStreaming())) { refresh(false);//from ww w . ja v a 2 s. c o m } } else if (needsRefresh || this.chartCache == null) { // No chart loaded. Doing a refresh will trigger a new // redraw later on. refresh(); return false; } JFreeChart jFreeChart = null; try { jFreeChart = ChartSwingUtil.createChartFromQuery(chartCache); if (jFreeChart == null) { g.drawString("Loading...", 0, g.getFontMetrics().getHeight()); return false; } Rectangle2D area = new Rectangle2D.Double(0, 0, width, height); // first pass establishes rendering info but draws nothing ChartRenderingInfo info = new ChartRenderingInfo(); Graphics2D dummyGraphics = (Graphics2D) g.create(0, 0, 0, 0); jFreeChart.draw(dummyGraphics, area, info); dummyGraphics.dispose(); // now for real Rectangle2D plotArea = info.getPlotInfo().getDataArea(); ChartGradientPainter.paintChartGradient(g, area, (int) plotArea.getMaxY()); jFreeChart.draw(g, area); } catch (Exception e) { logger.error("Error while rendering chart", e); g.drawString("Could not render chart: " + e.getMessage(), 0, g.getFontMetrics().getHeight()); } return false; }
From source file:net.java.sip.communicator.impl.osdependent.jdic.SystrayServiceJdicImpl.java
private BufferedImage createOverlayImage(String text) { int size = 16; BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //background// www .j a v a 2s .c o m g.setPaint(new Color(0, 0, 0, 102)); g.fillRoundRect(0, 0, size, size, size, size); //filling int mainRadius = 14; g.setPaint(new Color(255, 98, 89)); g.fillRoundRect(size / 2 - mainRadius / 2, size / 2 - mainRadius / 2, mainRadius, mainRadius, size, size); //text Font font = g.getFont(); g.setFont(new Font(font.getName(), Font.BOLD, 9)); FontMetrics fontMetrics = g.getFontMetrics(); int textWidth = fontMetrics.stringWidth(text); g.setColor(Color.white); g.drawString(text, size / 2 - textWidth / 2, size / 2 - fontMetrics.getHeight() / 2 + fontMetrics.getAscent()); return image; }