List of usage examples for java.awt.geom Rectangle2D getBounds
public Rectangle getBounds()
From source file:PaintUtils.java
/** * Returns the bounds that the text of a label will be drawn into. * Takes into account the current font metrics. *///from ww w.j a v a 2s . c om public static Rectangle getTextBounds(Graphics g, JLabel label) { FontMetrics fm = g.getFontMetrics(); Rectangle2D r2d = fm.getStringBounds(label.getText(), g); Rectangle rect = r2d.getBounds(); int xOffset = 0; switch (label.getHorizontalAlignment()) { case SwingConstants.RIGHT: case SwingConstants.TRAILING: xOffset = label.getBounds().width - rect.width; break; case SwingConstants.CENTER: xOffset = (label.getBounds().width - rect.width) / 2; break; default: case SwingConstants.LEFT: case SwingConstants.LEADING: xOffset = 0; break; } int yOffset = 0; switch (label.getVerticalAlignment()) { case SwingConstants.TOP: yOffset = 0; break; case SwingConstants.CENTER: yOffset = (label.getBounds().height - rect.height) / 2; break; case SwingConstants.BOTTOM: yOffset = label.getBounds().height - rect.height; break; } return new Rectangle(xOffset, yOffset, rect.width, rect.height); }
From source file:net.sf.jasperreports.charts.util.SvgChartRendererFactory.java
@Override public Renderable getRenderable(JasperReportsContext jasperReportsContext, JFreeChart chart, ChartHyperlinkProvider chartHyperlinkProvider, Rectangle2D rectangle) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D grx = new SVGGraphics2D(document); grx.setSVGCanvasSize(rectangle.getBounds().getSize()); List<JRPrintImageAreaHyperlink> areaHyperlinks = null; if (chartHyperlinkProvider != null && chartHyperlinkProvider.hasHyperlinks()) { areaHyperlinks = ChartUtil.getImageAreaHyperlinks(chart, chartHyperlinkProvider, grx, rectangle); } else {/* w w w . java 2s .c o m*/ chart.draw(grx, rectangle); } try { StringWriter swriter = new StringWriter(); grx.stream(swriter); byte[] svgData = null; try { svgData = swriter.getBuffer().toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new JRRuntimeException(e); } return new SimpleRenderToImageAwareDataRenderer(svgData, areaHyperlinks); } catch (SVGGraphics2DIOException e) { throw new JRRuntimeException(e); } }
From source file:org.jdal.swing.form.SimpleBoxFormBuilder.java
/** * Add a component with label, increments cursor by two. * @param name label string/*from w ww.java 2 s . c o m*/ * @param c component. */ public void add(String name, Component c) { JLabel label = new JLabel(name); add(label); Rectangle2D rec = label.getFontMetrics(label.getFont()).getStringBounds(name, container.getGraphics()); setMaxWidth(rec.getBounds().width + 10); add(c); }
From source file:com.igormaznitsa.sciareto.ui.editors.MMDEditor.java
@Override public void onEnsureVisibilityOfTopic(@Nonnull final MindMapPanel source, @Nullable final Topic topic) { SwingUtilities.invokeLater(new Runnable() { @Override//from w w w. jav a2 s. c o m public void run() { if (topic == null) { return; } final AbstractElement element = (AbstractElement) topic.getPayload(); if (element == null) { return; } final Rectangle2D orig = element.getBounds(); final int GAP = 30; final Rectangle bounds = orig.getBounds(); bounds.setLocation(Math.max(0, bounds.x - GAP), Math.max(0, bounds.y - GAP)); bounds.setSize(bounds.width + GAP * 2, bounds.height + GAP * 2); final JViewport viewport = getViewport(); final Rectangle visible = viewport.getViewRect(); if (visible.contains(bounds)) { return; } bounds.setLocation(bounds.x - visible.x, bounds.y - visible.y); viewport.scrollRectToVisible(bounds); } }); }
From source file:net.sf.maltcms.chromaui.charts.FastHeatMapPlot.java
/** * Draws a representation of the data within the dataArea region. The * <code>info</code> and <code>crosshairState</code> arguments may be * <code>null</code>./*from ww w . j a v a2 s.c o m*/ * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param info an optional object for collection dimension information. * @param crosshairState collects crosshair information (<code>null</code> * permitted). */ public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) { // long start = System.currentTimeMillis(); // System.out.println("Start: " + start); //System.out.println("Data area: " + dataArea); // g2.setPaint(this.paint); // if the axes use a linear scale, you can uncomment the code below and // switch to the alternative transX/transY calculation inside the loop // that follows - it is a little bit faster then. // // int xx = (int) dataArea.getMinX(); // int ww = (int) dataArea.getWidth(); // int yy = (int) dataArea.getMaxY(); // int hh = (int) dataArea.getHeight(); // double domainMin = this.domainAxis.getLowerBound(); // double domainLength = this.domainAxis.getUpperBound() - domainMin; // double rangeMin = this.rangeAxis.getLowerBound(); // double rangeLength = this.rangeAxis.getUpperBound() - rangeMin; if (this.dataImage != null) { Logger.getLogger(getClass().getName()).info("Drawing data image"); //DATA SPACE // System.out.println("Domain axis lower bound: "+this.domainAxis.getLowerBound()); // define ROI in data coordinates double xlb = this.domainAxis.getLowerBound(); double ylb = this.rangeAxis.getLowerBound(); double xub = this.domainAxis.getUpperBound(); double yub = this.rangeAxis.getUpperBound(); //construct region of interest for data in view Rectangle2D.Double roi = new Rectangle2D.Double(xlb, ylb, xub - xlb, yub - ylb); Logger.getLogger(getClass().getName()).log(Level.INFO, "ROI: {0}", roi); //construct bounding rectangle of data Rectangle2D.Double imgSpace = new Rectangle2D.Double(0, 0, this.dataImage.getWidth(), this.dataImage.getHeight()); Logger.getLogger(getClass().getName()).log(Level.INFO, "IMG Space: {0}", imgSpace); //construct intersection of both, this is the area of the data, we need to render Rectangle2D sourceCoordinates = imgSpace.createIntersection(roi); Logger.getLogger(getClass().getName()).log(Level.INFO, "Projecting from: {0}", sourceCoordinates); //VIEW SPACE // define mapping coordinates from data domain to view domain double xlow = this.domainAxis.valueToJava2D(this.domainAxis.getLowerBound(), dataArea, RectangleEdge.BOTTOM); double ylow = this.rangeAxis.valueToJava2D(this.rangeAxis.getLowerBound(), dataArea, RectangleEdge.LEFT); double xhigh = this.domainAxis.valueToJava2D(this.domainAxis.getUpperBound(), dataArea, RectangleEdge.TOP); double yhigh = this.rangeAxis.valueToJava2D(this.rangeAxis.getUpperBound(), dataArea, RectangleEdge.RIGHT); drawFromOffscreenBuffer(g2, this.dataImage, sourceCoordinates.getBounds(), dataArea.getBounds()); renderCrosshairs(dataArea, g2); } else { createImage(g2, dataArea, info, crosshairState); render(g2, dataArea, info, crosshairState); } }
From source file:org.deegree.portal.standard.wms.control.DynLegendListener.java
/** * In case the legend can not be obtained from the OGCLayer, this method is called to create a dummy legend image * plus the legend title/*from w w w .j a va 2s .c om*/ * * @param layerName * @return BufferedImage holding the created dummy legend */ private BufferedImage createMissingLegend(String layerName) { LOG.logDebug("URL is null. Drawing the image from a missingImage variable in init params"); BufferedImage missingLegend = new BufferedImage(80, 15, BufferedImage.TYPE_INT_RGB); Graphics g = missingLegend.getGraphics(); Rectangle2D rect = g.getFontMetrics().getStringBounds(layerName, g); g.dispose(); missingLegend = new BufferedImage(rect.getBounds().width + 80, missingImg.getHeight() + 15, BufferedImage.TYPE_INT_ARGB); g = missingLegend.getGraphics(); g.drawImage(missingImg, 0, 0, null); g.setColor(Color.RED); if (useLayerTitle) { g.drawString(layerName, missingImg.getWidth() + 5, missingImg.getHeight() / 2 + g.getFont().getSize() / 2); } g.dispose(); return missingLegend; }
From source file:org.geotools.coverage.io.util.Utilities.java
/** * Return a crop region from a specified envelope, leveraging on a grid to world transformation. * //from w ww . j av a2 s .c o m * @param envelope the crop envelope * @param gridToWorldTransform the grid2world transformation * @return a {@code Rectangle} representing the crop region. * @throws TransformException in case a problem occurs when going back to raster space. */ public static Rectangle getCropRegion(GeneralEnvelope envelope, final MathTransform gridToWorldTransform) throws TransformException { if (envelope == null || gridToWorldTransform == null) { boolean isEnvelope = envelope == null; boolean isG2W = gridToWorldTransform == null; boolean twoErrors = isEnvelope && isG2W; final StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Specified ").append(isEnvelope ? "envelope" : "").append(twoErrors ? ", " : "") .append(isG2W ? "grid to world transformation " : "").append("is null"); throw new IllegalArgumentException(errorMessage.toString()); } final MathTransform worldToGridTransform = gridToWorldTransform.inverse(); final GeneralEnvelope rasterArea = CRS.transform(worldToGridTransform, envelope); final Rectangle2D ordinates = rasterArea.toRectangle2D(); return ordinates.getBounds(); }
From source file:org.geotools.coverage.io.util.Utilities.java
/** * Returns the intersection between the base envelope and the requested envelope. * /* w ww . j a v a 2 s. com*/ * @param baseEnvelope2D the base envelope. * * @param requestedEnvelope2D the requested 2D envelope to be intersected with the base envelope. * @param requestedDim is the requested region where to load data of the specified envelope. * @param readGridToWorld the Grid to world transformation to be used in read * @param wgs84BaseEnvelope2D a WGS84 version of the baseEnvelope to be used to try finding an intersection in wgs84 in case it is impossible to * compute an intersection of the base envelope with the specified requested envelope. * @return the resulting intersection of envelopes. In case of empty intersection, this method is allowed to return {@code null} * @throws TransformException * @throws FactoryException * @todo TODO XXX refactor this method leveraging on the coverageSourceCapabilities of reprojection. Moreover add a boolean parameter saying if * trying to reproject to WGS84 always need to be done */ public static GeneralEnvelope getIntersection(final Envelope2D baseEnvelope2D, final CoordinateReferenceSystem spatialReferenceSystem2D, GeneralEnvelope requestedEnvelope2D, Rectangle requestedDim, MathTransform2D readGridToWorld, final Envelope2D wgs84BaseEnvelope2D) throws TransformException, FactoryException { if (baseEnvelope2D == null || spatialReferenceSystem2D == null || requestedEnvelope2D == null || requestedDim == null || readGridToWorld == null) { StringBuilder sb = new StringBuilder("Some of the specified parameters are null:") .append(baseEnvelope2D == null ? "base envelope \n" : "") .append(spatialReferenceSystem2D == null ? "native spatial reference system\n" : "") .append(requestedEnvelope2D == null ? "requested envelope \n" : "") .append(requestedDim == null ? "requested dim\n" : "") .append(readGridToWorld == null ? "requested grid to world transformation \n" : ""); throw new IllegalArgumentException(sb.toString()); } GeneralEnvelope adjustedRequestedEnvelope = new GeneralEnvelope(2); final CoordinateReferenceSystem requestedEnvelopeCRS2D = requestedEnvelope2D.getCoordinateReferenceSystem(); boolean tryWithWGS84 = false; try { // convert the requested envelope 2D to this coverage native crs. MathTransform transform = null; if (!CRS.equalsIgnoreMetadata(requestedEnvelopeCRS2D, spatialReferenceSystem2D)) transform = CRS.findMathTransform(requestedEnvelopeCRS2D, spatialReferenceSystem2D, true); // now transform the requested envelope to source crs if (transform != null && !transform.isIdentity()) adjustedRequestedEnvelope = CRS.transform(transform, requestedEnvelope2D); else adjustedRequestedEnvelope.setEnvelope(requestedEnvelope2D); // intersect the requested area with the bounds of this // layer in native crs if (!adjustedRequestedEnvelope.intersects(baseEnvelope2D, true)) return null; adjustedRequestedEnvelope.intersect(baseEnvelope2D); adjustedRequestedEnvelope.setCoordinateReferenceSystem(spatialReferenceSystem2D); // // // // transform the intersection envelope from the destination world // space to the requested raster space // // // final Envelope requestedEnvelopeCropped = (transform != null && !transform.isIdentity()) ? CRS.transform(transform.inverse(), adjustedRequestedEnvelope) : adjustedRequestedEnvelope; final Rectangle2D ordinates = CRS.transform(readGridToWorld.inverse(), requestedEnvelopeCropped) .toRectangle2D(); final GeneralGridEnvelope finalRange = new GeneralGridEnvelope(ordinates.getBounds()); final Rectangle tempRect = finalRange.toRectangle(); // check that we stay inside the source rectangle XRectangle2D.intersect(tempRect, requestedDim, tempRect); requestedDim.setRect(tempRect); } catch (TransformException te) { // something bad happened while trying to transform this // envelope. let's try with wgs84 tryWithWGS84 = true; } catch (FactoryException fe) { // something bad happened while trying to transform this // envelope. let's try with wgs84 tryWithWGS84 = true; } // // // // If this does not work, we go back to reproject in the wgs84 // requested envelope // // // if (tryWithWGS84) { final GeneralEnvelope requestedEnvelopeWGS84 = (GeneralEnvelope) getEnvelopeAsWGS84(requestedEnvelope2D, false); // checking the intersection in wgs84 if (!requestedEnvelopeWGS84.intersects(wgs84BaseEnvelope2D, true)) return null; // intersect adjustedRequestedEnvelope = new GeneralEnvelope(requestedEnvelopeWGS84); adjustedRequestedEnvelope.intersect(wgs84BaseEnvelope2D); adjustedRequestedEnvelope = CRS .transform(CRS.findMathTransform(requestedEnvelopeWGS84.getCoordinateReferenceSystem(), spatialReferenceSystem2D, true), adjustedRequestedEnvelope); adjustedRequestedEnvelope.setCoordinateReferenceSystem(spatialReferenceSystem2D); } return adjustedRequestedEnvelope; }
From source file:org.kalypsodeegree_impl.graphics.displayelements.LabelFactory.java
/** * Generates <tt>Label</tt> -representations for a given <tt>LabelDisplayElement</tt>. *///from www . j av a 2s.c om public Label[] createLabels() throws GM_Exception { try { final Feature feature = m_element.getFeature(); final String caption = m_element.getLabel().evaluate(feature); // sanity check: empty labels are ignored if (StringUtils.isBlank(caption)) return EMPTY_LABELS; // gather font information final org.kalypsodeegree.graphics.sld.Font sldFont = m_symbolizer.getFont(); final java.awt.Font font = new java.awt.Font(sldFont.getFamily(feature), sldFont.getStyle(feature) | sldFont.getWeight(feature), sldFont.getSize(feature)); m_graphics.setFont(font); final Color color = sldFont.getColor(feature); final FontRenderContext frc = m_graphics.getFontRenderContext(); // bugstories... // I got the following error in the next line: // # An unexpected error has been detected by HotSpot Virtual Machine: // # [...] // # Problematic frame: // # C [libfontmanager.so+0x2ecd5] // // while running kalypso on linux, kubuntu-Dapper. // The error was caused by some buggy fonts in Dapper (Rekha-normal and aakar-MagNet ). // Work-around is to remove the toxic fonts by removing the package ttf-gujarati-fonts from the distribution. // this error was not easy to locate, so do not remove this notice ! // ( v.doemming@tuhh.de ) final Rectangle2D bounds = font.getStringBounds(caption, frc); final Dimension size = bounds.getBounds().getSize(); final LineMetrics metrics = font.getLineMetrics(caption, frc); final GM_Object[] geometries = m_element.getGeometry(); final List<Label> allLabels = new ArrayList<>(); for (final GM_Object geometry : geometries) { final Label[] labels = createLabels(feature, caption, geometry, font, color, metrics, size); allLabels.addAll(Arrays.asList(labels)); } return allLabels.toArray(new Label[allLabels.size()]); } catch (final FilterEvaluationException e) { // if properties are unknown to features, this should be ignored! return EMPTY_LABELS; } }