Example usage for java.awt.geom Rectangle2D getWidth

List of usage examples for java.awt.geom Rectangle2D getWidth

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D getWidth.

Prototype

public abstract double getWidth();

Source Link

Document

Returns the width of the framing rectangle in double precision.

Usage

From source file:net.sourceforge.processdash.ui.lib.chart.DiscLegendAxis.java

/**
 * The superclass' drawAxisLine() method draws the axis line for the entire
 *  dataArea's length. Since we want the line to end at the height of the maximum
 *  shown tick, we create a new Rectangle2D with the appropriate dimensions.
 *///www . j ava  2 s .  c o  m
@Override
protected void drawAxisLine(Graphics2D g2, double cursor, Rectangle2D dataArea, RectangleEdge edge) {

    // In the original flow of events, the refreshing of the ticks is made after
    //  drawing the axis line. Since this implementation needs the ticks to be
    //  set properly, we force a tick refresh.
    AxisState state = new AxisState(cursor);
    refreshTicks(g2, state, dataArea, edge);

    double amountBetweenTicks = getTickUnit().getSize();
    int tickCount = calculateVisibleTickCount() - 1;
    double lowestTickValue = calculateLowestVisibleTickValue();

    double minY = valueToJava2D(lowestTickValue + tickCount * amountBetweenTicks, dataArea, edge);
    double maxY = valueToJava2D(lowestTickValue, dataArea, edge);
    double height = maxY - minY;

    Rectangle2D axisLineArea = new Rectangle2D.Double(dataArea.getX(), minY, dataArea.getWidth(), height);

    super.drawAxisLine(g2, cursor, axisLineArea, edge);
}

From source file:soap.ui.stats.LineAndShapeRendererMapToBar.java

public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,
        CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column) {

    // nothing is drawn for null...
    Number v = dataset.getValue(row, column);
    if (v == null)
        return;/*from  w w w.java2 s . com*/

    PlotOrientation orientation = plot.getOrientation();

    // current data point which is associated to a serie...
    double x1 = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge());
    int seriesCount = mBarRenderer.getPlot().getDataset().getRowCount();
    int categoryCount = mBarRenderer.getPlot().getDataset().getColumnCount();
    if (seriesCount > 1 && mNumSerie < seriesCount) {
        double seriesGap = dataArea.getWidth() * 0.2 / (categoryCount * (seriesCount - 1));
        double seriesW = calculateSeriesWidth(dataArea.getWidth(), domainAxis, categoryCount, seriesCount);
        x1 = x1 + mNumSerie * (seriesW + seriesGap) + (seriesW / 2.0) - (state.getBarWidth() / 2.0);

    } else {
        x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge());
    }

    double value = v.doubleValue();
    double y1 = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());

    Shape shape = getItemShape(row, column);
    if (orientation == PlotOrientation.HORIZONTAL) {
        shape = createTransformedShape(shape, y1, x1);
    } else if (orientation == PlotOrientation.VERTICAL) {
        shape = createTransformedShape(shape, x1, y1);
    }
    if (isDrawShapes()) {
        if (getItemShapeFilled(row, column)) {
            g2.setPaint(getItemPaint(row, column));
            g2.fill(shape);
        } else {
            g2.setPaint(getItemOutlinePaint(row, column));
            g2.setStroke(getItemOutlineStroke(row, column));
            g2.draw(shape);
        }
    }

    if (isDrawLines()) {
        if (column != 0) {
            Number previousValue = dataset.getValue(row, column - 1);
            if (previousValue != null) {
                // previous data point...
                double previous = previousValue.doubleValue();
                double x0 = domainAxis.getCategoryStart(column - 1, getColumnCount(), dataArea,
                        plot.getDomainAxisEdge());
                //  seriesCount = getRowCount();
                //  categoryCount = getColumnCount();
                if (seriesCount > 1 && mNumSerie < seriesCount) {
                    double seriesGap = dataArea.getWidth() * 0.2 / (categoryCount * (seriesCount - 1));
                    double seriesW = calculateSeriesWidth(dataArea.getWidth(), domainAxis, categoryCount,
                            seriesCount);
                    x0 = x0 + mNumSerie * (seriesW + seriesGap) + (seriesW / 2.0) - (state.getBarWidth() / 2.0);
                } else {
                    x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea,
                            plot.getDomainAxisEdge());
                }

                double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge());

                Line2D line = null;
                if (orientation == PlotOrientation.HORIZONTAL) {
                    line = new Line2D.Double(y0, x0, y1, x1);
                } else if (orientation == PlotOrientation.VERTICAL) {
                    line = new Line2D.Double(x0, y0, x1, y1);
                }
                g2.setPaint(getItemPaint(row, column));
                g2.setStroke(getItemStroke(row, column));
                g2.draw(line);
            }
        }
    }

    // draw the item label if there is one...
    if (isItemLabelVisible(row, column)) {
        if (orientation == PlotOrientation.HORIZONTAL) {
            drawItemLabel(g2, orientation, dataset, row, column, y1, x1, (value < 0.0));
        } else if (orientation == PlotOrientation.VERTICAL) {
            drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value < 0.0));
        }
    }

    // collect entity and tool tip information...
    if (state.getInfo() != null) {
        EntityCollection entities = state.getInfo().getOwner().getEntityCollection();
        if (entities != null && shape != null) {
            String tip = null;
            CategoryToolTipGenerator tipster = getToolTipGenerator(row, column);
            if (tipster != null) {
                tip = tipster.generateToolTip(dataset, row, column);
            }
            String url = null;
            if (getItemURLGenerator(row, column) != null) {
                url = getItemURLGenerator(row, column).generateURL(dataset, row, column);
            }
            CategoryItemEntity entity = new CategoryItemEntity(shape, tip, url, dataset, row,
                    dataset.getColumnKey(column), column);
            entities.addEntity(entity);
        }
    }
}

From source file:net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.java

protected TextLine measureLine(float width, boolean requireWord, int endLimit) {
    // try to guess how much of the text would fit based on the average char width
    int measureIndex = estimateBreakIndex(width, endLimit);

    // if estimating that there's more than a line, check measureExactMultiline
    if (measureIndex < endLimit && measureExactMultiline) {
        return measureExactLine(width, endLimit, requireWord);
    }/*from   w  ww . j av a 2s . c om*/

    // measure the text
    Rectangle2D bounds = measureParagraphFragment(measureIndex);
    //FIXME fast exit when the height is exceeded

    Rectangle2D measuredBounds = bounds;
    if (bounds.getWidth() <= width) {
        // see if there's more that could fit
        boolean done = false;
        do {
            int nextBreakIndex = measureIndex < endLimit ? paragraphBreakIterator.following(measureIndex)
                    : BreakIterator.DONE;
            if (nextBreakIndex == BreakIterator.DONE || nextBreakIndex > endLimit) {
                // the next break is after the limit, we're done
                done = true;
            } else {
                // measure to the next break
                Rectangle2D nextBounds = measureParagraphFragment(nextBreakIndex);
                if (nextBounds.getWidth() <= width) {
                    measuredBounds = nextBounds;
                    measureIndex = nextBreakIndex;
                    // loop
                } else {
                    done = true;
                }
            }
        } while (!done);
    } else {
        // didn't fit, try shorter texts
        boolean done = false;
        do {
            int previousBreakIndex = measureIndex > paragraphPosition
                    ? paragraphBreakIterator.preceding(measureIndex)
                    : BreakIterator.DONE;
            if (previousBreakIndex == BreakIterator.DONE || previousBreakIndex <= paragraphPosition) {
                if (requireWord) {
                    // no full word fits, returning empty
                    measureIndex = paragraphPosition;
                } else {
                    // we need to break inside the word.
                    // measuring the exact break index as estimating/guessing might be slower.
                    measureIndex = measureExactLineBreakIndex(width, endLimit, requireWord);
                    measuredBounds = measureParagraphFragment(measureIndex);
                }
                done = true;
            } else {
                measureIndex = previousBreakIndex;
                Rectangle2D prevBounds = measureParagraphFragment(measureIndex);
                if (prevBounds.getWidth() <= width) {
                    // fitted, we're done
                    measuredBounds = prevBounds;
                    done = true;
                }
            }
        } while (!done);
    }

    if (measureIndex <= paragraphPosition) {
        // nothing fit
        return null;
    }
    return toTextLine(measureIndex, measuredBounds);
}

From source file:org.tsho.dmc2.core.chart.BifurcationSimpleRenderer.java

public void render(final Graphics2D g2, final Rectangle2D dataArea, PlotRenderingInfo info) {

    if (model instanceof ODE) {
        boolean pointBeyondPoincareSection;
        int numVar = model.getNVar();

        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        Stepper.Point2D result;/*  w  ww  .  j a v  a2 s.  c  om*/

        g2.setPaint(plot.getPaint());

        parLower = domainAxis.getRange().getLowerBound();
        parUpper = domainAxis.getRange().getUpperBound();
        final double parStep;

        parStep = Math.abs(parUpper - parLower) / dataArea.getWidth();

        stepper.setAxes(variableIdx, variableIdx);

        state = STATE_RUNNING;

        for (index = parLower; index < parUpper; index += parStep) {

            fixedParameters[parameterIdx] = index;

            stepper.setParameters(fixedParameters);
            stepper.setInitialValue(initialValue);
            stepper.initialize();

            int h = 0;
            int transX, transY;

            double[] currentPoint = new double[numVar];
            double[] previousPoint = new double[numVar];
            stepper.getCurrentValue(currentPoint);
            stepper.getCurrentValue(previousPoint);
            pointBeyondPoincareSection = positionWrtPoincareSection(currentPoint);

            for (int j = 0; j < time / step; j++) {
                stepper.step();
                stepper.getCurrentValue(currentPoint);

                if (positionWrtPoincareSection(currentPoint) == pointBeyondPoincareSection) {
                    stepper.getCurrentValue(previousPoint);
                    continue;
                }

                pointBeyondPoincareSection = !pointBeyondPoincareSection;
                double[] pointOnSection = pointOnPoincareSection(previousPoint, currentPoint);
                stepper.setInitialValue(pointOnSection);
                stepper.initialize();
                stepper.getCurrentValue(currentPoint);
                stepper.getCurrentValue(previousPoint);

                //pointBeyondPoincareSection=positionWrtPoincareSection(currentPoint,coeff);
                result = stepper.getCurrentPoint2D();

                transX = (int) domainAxis.valueToJava2D(index, dataArea, RectangleEdge.BOTTOM);

                transY = (int) rangeAxis.valueToJava2D(result.getX(), dataArea, RectangleEdge.LEFT);

                h++;
                if (h > transients) {
                    g2.fillRect(transX, transY, 1, 1);
                }

            }

            if (!fixedInitialPoint) {
                stepper.getCurrentValue(initialValue);
            }

            if (stopped) {
                state = STATE_STOPPED;
                return;
            }
        }

        state = STATE_FINISHED;
    } else {
        //the system is discrete
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        Stepper.Point2D result;

        g2.setPaint(plot.getPaint());

        parLower = domainAxis.getRange().getLowerBound();
        parUpper = domainAxis.getRange().getUpperBound();
        final double parStep;

        parStep = Math.abs(parUpper - parLower) / dataArea.getWidth();

        stepper.setAxes(variableIdx, variableIdx);

        state = STATE_RUNNING;

        for (index = parLower; index < parUpper; index += parStep) {

            fixedParameters[parameterIdx] = index;

            stepper.setParameters(fixedParameters);
            stepper.setInitialValue(initialValue);
            stepper.initialize();

            for (int h = 0; h < transients; h++) {
                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }

                stepper.step();
            }

            int transX, transY;
            for (int j = 0; j < iterations; j++) {

                stepper.step();

                result = stepper.getCurrentPoint2D();

                transX = (int) domainAxis.valueToJava2D(index, dataArea, RectangleEdge.BOTTOM);

                transY = (int) rangeAxis.valueToJava2D(result.getX(), dataArea, RectangleEdge.LEFT);

                g2.fillRect(transX, transY, 1, 1);
            }

            if (!fixedInitialPoint) {
                stepper.getCurrentValue(initialValue);
            }

            if (stopped) {
                state = STATE_STOPPED;
                return;
            }
        }
        state = STATE_FINISHED;
    }

}

From source file:org.tsho.dmc2.core.chart.DmcLyapunovPlot.java

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    CoreStatusEvent statusEv = new CoreStatusEvent(this);
    g2.setPaint(paint);/*from  www  .j  a v a  2s.  co  m*/

    final double parHStep, parVStep;
    double parHLower = domainAxis.getRange().getLowerBound();
    double parHUpper = domainAxis.getRange().getUpperBound();
    double parVLower = rangeAxis.getRange().getLowerBound();
    double parVUpper = rangeAxis.getRange().getUpperBound();

    parHStep = Math.abs(parHUpper - parHLower) / dataArea.getWidth();
    parVStep = Math.abs(parVUpper - parVLower) / dataArea.getHeight();

    final BufferedImage image = new BufferedImage((int) dataArea.getWidth(), (int) dataArea.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int[] data = dataBuffer.getData();

    final double parHStart = parHLower + parHStep / 2;
    final double parVStart = parVUpper - parVStep / 2;

    for (int i = 0; i < (int) dataArea.getWidth(); i++) {
        for (int j = 0; j < (int) dataArea.getHeight(); j++) {

            parameters.put(firstParLabel, parHStart + i * parHStep);
            parameters.put(secondParLabel, parVStart - j * parVStep);

            double[] result;
            int color;

            try {
                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);
            } catch (ModelException e) {
                String mess = "Exception while:\n" + dumpVariableDoubles(parameters)
                        + dumpVariableDoubles(initialPoint);
                throw new ModelException(mess, e);
            }

            if (result == null) {
                System.out.println("i: " + i + " j: " + j);
                System.out.println("par1: " + parHStart + i * parHStep);
                System.out.println("par2: " + parVStart + j * parVStep);
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setStatusString("exception");
                statusEv.setType(CoreStatusEvent.STRING);
                notifyCoreStatusListeners(statusEv);
                return false;
            }

            // both zero
            if (Math.abs(result[0]) < epsilon && Math.abs(result[1]) < epsilon) {
                color = Color.black.getRGB();
            }
            // one zero one positive
            else if (Math.abs(result[0]) < epsilon && result[1] > 0
                    || Math.abs(result[1]) < epsilon && result[0] > 0) {
                color = Color.red.getRGB();
            }
            // one zero one negative
            else if (Math.abs(result[0]) < epsilon && result[1] < 0
                    || Math.abs(result[1]) < epsilon && result[0] < 0) {
                color = Color.blue.getRGB();
            }
            // one positive one negative
            else if (result[0] < 0 && result[1] > 0 || result[1] < 0 && result[0] > 0) {
                color = Color.green.getRGB();
            }
            // both positive
            else if (result[0] > 0 && result[1] > 0) {
                color = Color.orange.getRGB();
            }
            // both negative
            else if (result[0] < 0 && result[1] < 0) {
                color = Color.pink.getRGB();
            } else { // impossible
                color = Color.yellow.getRGB();
            }

            data[i + j * (int) dataArea.getWidth()] = color;

            if (stopped == true) {
                return false;
            }
            if (j == (int) dataArea.getHeight() - 1) {
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setPercent(0);
                statusEv.setType(CoreStatusEvent.COUNT | CoreStatusEvent.PERCENT);
                notifyCoreStatusListeners(statusEv);
            }
        }
    }

    return true;
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

private Shape convertObstacle(final Obstacle2D o) {
    final Rectangle2D r = o.getBounds2D();
    final Position[] points = new Position[] { new Continuous2DEuclidean(r.getX(), r.getY()),
            new Continuous2DEuclidean(r.getX() + r.getWidth(), r.getY()),
            new Continuous2DEuclidean(r.getX() + r.getWidth(), r.getY() + r.getHeight()),
            new Continuous2DEuclidean(r.getX(), r.getY() + r.getHeight()) };
    final Path2D path = new GeneralPath();
    for (int i = 0; i < points.length; i++) {
        final Point pt = wormhole.getViewPoint(points[i]);
        if (i == 0) {
            path.moveTo(pt.getX(), pt.getY());
        }//from  w ww. j  av a 2s . c  o m
        path.lineTo(pt.getX(), pt.getY());
    }
    path.closePath();
    return path;
}

From source file:org.jax.haplotype.analysis.visualization.SimplePhylogenyTreeImageFactory.java

/**
 * Transform the tree layout so that it fits nicely in the given image
 * dimensions/*from  w ww .  ja v  a  2  s  . c  o  m*/
 * @param treeLayout
 *          the layout to transform
 * @param imageWidth
 *          the image width
 * @param imageHeight
 *          the image height
 */
private void transformTreeLayout(VisualTreeNode treeLayout, int imageWidth, int imageHeight,
        FontRenderContext frc) {
    Dimension2D maximalNodeLabelDimension = this.calculateMaximalNodeDimension(treeLayout, frc);
    double widthBuffer = maximalNodeLabelDimension.getWidth() + BORDER_WHITE_SPACE;
    double heightBuffer = maximalNodeLabelDimension.getHeight() + BORDER_WHITE_SPACE;

    // perform rotation to improve the use of space
    {
        // center around 0, 0
        VisualTreeNode[] mostDistantPair = this.getMostDistantNodePair(treeLayout);
        Point2D distantPoint1 = mostDistantPair[0].getPosition();
        Point2D distantPoint2 = mostDistantPair[1].getPosition();
        double xDiff = distantPoint1.getX() - distantPoint2.getX();
        double yDiff = distantPoint1.getY() - distantPoint2.getY();
        this.translateTreeLayout(treeLayout, (xDiff / 2.0) - distantPoint1.getX(),
                (yDiff / 2.0) - distantPoint2.getY());

        // rotate
        double thetaRadians = Math.atan2(yDiff, xDiff);

        if (imageWidth >= imageHeight) {
            this.rotateTreeLayout(treeLayout, -thetaRadians);
        } else {
            this.rotateTreeLayout(treeLayout, (Math.PI / 2.0 - thetaRadians));
        }
    }

    Rectangle2D boundingRectangle = this.calculateBounds(treeLayout, null);

    // center around the middle of the display area
    this.translateTreeLayout(treeLayout, -boundingRectangle.getX(), -boundingRectangle.getY());

    // grow the image to fill a larger area
    double xScale = (imageWidth - widthBuffer) / boundingRectangle.getWidth();
    double yScale = (imageHeight - heightBuffer) / boundingRectangle.getHeight();
    double smallerScale = Math.min(xScale, yScale);

    this.scaleTreeLayout(treeLayout, smallerScale);

    // center around the middle of the display area
    boundingRectangle = this.calculateBounds(treeLayout, null);
    this.translateTreeLayout(treeLayout,
            ((imageWidth - boundingRectangle.getWidth()) / 2.0) - boundingRectangle.getX(),
            ((imageHeight - boundingRectangle.getHeight()) / 2.0) - boundingRectangle.getY());
}

From source file:net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.java

protected Rectangle2D measureParagraphFragment(int measureIndex) {
    int endIndex = measureIndex;
    if (endIndex > paragraphPosition + 1) {
        char lastMeasureChar = paragraphText.charAt(endIndex - 1);
        if (Character.isWhitespace(lastMeasureChar)) {
            // exclude trailing white space from the text to measure.
            // use the previous break as limit, but always keep at least one character to measure.
            int preceding = paragraphBreakIterator.preceding(endIndex);
            if (preceding == BreakIterator.DONE || preceding <= paragraphPosition) {
                preceding = paragraphPosition + 1;
            }/*  w w  w  .  j  a  v a  2 s  .  co  m*/

            do {
                --endIndex;
                lastMeasureChar = paragraphText.charAt(endIndex - 1);
            } while (endIndex > preceding && Character.isWhitespace(lastMeasureChar));
        }
    }

    // note that trailing white space will not be included in the advance
    Rectangle2D bounds = fontInfo.fontInfo.font.getStringBounds(paragraphText, paragraphPosition, endIndex,
            context.getFontRenderContext());

    // adding the measurement to the font info statistics
    fontInfo.recordMeasurement(bounds.getWidth() / (endIndex - paragraphPosition));

    if (logTrace) {
        log.trace("measured to index " + (endIndex + paragraphOffset) + " at width " + bounds.getWidth());
    }

    return bounds;
}

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  va2  s  .c om*/
    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.kalypsodeegree_impl.model.geometry.GM_Envelope_Impl.java

/**
 * returns a new GM_Envelope object representing the intersection of this GM_Envelope with the specified GM_Envelope.
 * * Note: If there is no intersection at all GM_Envelope will be null.
 * /*  w  ww  . j  a va 2s.  c  om*/
 * @param bb
 *          the GM_Envelope to be intersected with this GM_Envelope
 * @return the largest GM_Envelope contained in both the specified GM_Envelope and in this GM_Envelope.
 */
@Override
public GM_Envelope createIntersection(final GM_Envelope bb) {
    Rectangle2D rect = new Rectangle2D.Double(bb.getMin().getX(), bb.getMin().getY(), bb.getWidth(),
            bb.getHeight());
    final Rectangle2D rect2 = new Rectangle2D.Double(getMin().getX(), getMin().getY(), getWidth(), getHeight());

    if (rect2.intersects(bb.getMin().getX(), bb.getMin().getY(), bb.getWidth(), bb.getHeight())) {
        rect = rect.createIntersection(rect2);
    } else {
        rect = null;
    }

    if (rect == null) {
        return null;
    }

    final double xmin = rect.getX();
    final double ymin = rect.getY();
    final double xmax = rect.getX() + rect.getWidth();
    final double ymax = rect.getY() + rect.getHeight();

    // TODO Check coordinate systems, if equal.
    return new GM_Envelope_Impl(xmin, ymin, xmax, ymax, m_coordinateSystem);
}