Example usage for java.awt Shape getBounds2D

List of usage examples for java.awt Shape getBounds2D

Introduction

In this page you can find the example usage for java.awt Shape getBounds2D.

Prototype

public Rectangle2D getBounds2D();

Source Link

Document

Returns a high precision and more accurate bounding box of the Shape than the getBounds method.

Usage

From source file:edu.dlnu.liuwenpeng.render.BarRenderer.java

/**    
* Draws an item label.  This method is overridden so that the bar can be    
* used to calculate the label anchor point.    
*    /*from   ww  w . j av a2 s  .c o m*/
* @param g2  the graphics device.    
* @param data  the dataset.    
* @param row  the row.    
* @param column  the column.    
* @param plot  the plot.    
* @param generator  the label generator.    
* @param bar  the bar.    
* @param negative  a flag indicating a negative value.    
*/
protected void drawItemLabel(Graphics2D g2, CategoryDataset data, int row, int column, CategoryPlot plot,
        CategoryItemLabelGenerator generator, Rectangle2D bar, boolean negative) {

    String label = generator.generateLabel(data, row, column);
    if (label == null) {
        return; // nothing to do    
    }

    Font labelFont = getItemLabelFont(row, column);
    g2.setFont(labelFont);
    Paint paint = getItemLabelPaint(row, column);
    g2.setPaint(paint);

    // find out where to place the label...    
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(row, column);
    } else {
        position = getNegativeItemLabelPosition(row, column);
    }

    // work out the label anchor point...    
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar, plot.getOrientation());

    if (isInternalAnchor(position.getItemLabelAnchor())) {
        Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(),
                (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                position.getRotationAnchor());

        if (bounds != null) {
            if (!bar.contains(bounds.getBounds2D())) {
                if (!negative) {
                    position = getPositiveItemLabelPositionFallback();
                } else {
                    position = getNegativeItemLabelPositionFallback();
                }
                if (position != null) {
                    anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                            plot.getOrientation());
                }
            }
        }

    }

    if (position != null) {
        TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(),
                position.getTextAnchor(), position.getAngle(), position.getRotationAnchor());
    }
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Passed Line's point2 must be inside the passed shape or
 * an IllegalArgumentException is thrown
 * @param line line to subdivide//from ww  w. j av a 2  s  .  co  m
 * @param shape shape to compare with line
 * @return a line that intersects the shape boundary
 * @throws IllegalArgumentException if the passed line's point1 is not inside the shape
 */
protected Line2D getLastOutsideSegment(Line2D line, Shape shape) {
    if (shape.contains(line.getP2()) == false) {
        String errorString = "line end point: " + line.getP2() + " is not contained in shape: "
                + shape.getBounds2D();
        throw new IllegalArgumentException(errorString);
        //return null;
    }
    Line2D left = new Line2D.Double();
    Line2D right = new Line2D.Double();
    // subdivide the line until its left segment intersects
    // the shape boundary
    int iterations = 0;
    do {
        subdivide(line, left, right);
        line = right;
    } while (shape.contains(line.getP1()) == false && iterations++ < MAX_ITERATIONS);
    // now that right is completely inside shape,
    // return left, which must be partially outside
    return left;
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Passed Line's point1 must be inside the passed shape or
 * an IllegalArgumentException is thrown
 * @param line line to subdivide/*from  ww  w  . j  ava2  s  .  c o m*/
 * @param shape shape to compare with line
 * @return a line that intersects the shape boundary
 * @throws IllegalArgumentException if the passed line's point1 is not inside the shape
 */
protected Line2D getFirstOutsideSegment(Line2D line, Shape shape) {

    if (shape.contains(line.getP1()) == false) {
        String errorString = "line start point: " + line.getP1() + " is not contained in shape: "
                + shape.getBounds2D();
        throw new IllegalArgumentException(errorString);
    }
    Line2D left = new Line2D.Float();
    Line2D right = new Line2D.Float();
    // subdivide the line until its right side intersects the
    // shape boundary
    do {
        subdivide(line, left, right);
        line = left;
    } while (shape.contains(line.getP2()) == false);
    // now that left is completely inside shape,
    // return right, which must be partially outside
    return right;
}

From source file:net.sf.maltcms.chromaui.annotations.PeakAnnotationRenderer.java

private void drawOutline(Shape entity, Graphics2D g2, Color fill, Color stroke, ChartPanel chartPanel,
        boolean scale, float alpha) {
    if (entity != null) {
        //System.out.println("Drawing entity with bbox: "+entity.getBounds2D());
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        Color c = g2.getColor();/*from   ww  w .  jav  a 2  s . co  m*/
        Composite comp = g2.getComposite();
        g2.clip(dataArea);
        g2.setColor(fill);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        JFreeChart chart = chartPanel.getChart();
        XYPlot plot = (XYPlot) chart.getPlot();
        ValueAxis xAxis = plot.getDomainAxis();
        ValueAxis yAxis = plot.getRangeAxis();
        RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
        RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
        Rectangle2D entityBounds = entity.getBounds2D();
        double viewX = xAxis.valueToJava2D(entityBounds.getCenterX(), dataArea, xAxisEdge);
        double viewY = yAxis.valueToJava2D(entityBounds.getCenterY(), dataArea, yAxisEdge);
        double viewW = xAxis.lengthToJava2D(entityBounds.getWidth(), dataArea, xAxisEdge);
        double viewH = yAxis.lengthToJava2D(entityBounds.getHeight(), dataArea, yAxisEdge);
        PlotOrientation orientation = plot.getOrientation();

        //transform model to origin (0,0) in model coordinates
        AffineTransform toOrigin = AffineTransform.getTranslateInstance(-entityBounds.getCenterX(),
                -entityBounds.getCenterY());
        //transform from origin (0,0) to model location
        AffineTransform toModelLocation = AffineTransform.getTranslateInstance(entityBounds.getCenterX(),
                entityBounds.getCenterY());
        //transform from model scale to view scale
        double scaleX = viewW / entityBounds.getWidth();
        double scaleY = viewH / entityBounds.getHeight();
        Logger.getLogger(getClass().getName()).log(Level.FINE, "Scale x: {0} Scale y: {1}",
                new Object[] { scaleX, scaleY });
        AffineTransform toViewScale = AffineTransform.getScaleInstance(scaleX, scaleY);
        AffineTransform toViewLocation = AffineTransform.getTranslateInstance(viewX, viewY);
        AffineTransform flipTransform = AffineTransform.getScaleInstance(1.0f, -1.0f);
        AffineTransform modelToView = new AffineTransform(toOrigin);
        modelToView.preConcatenate(flipTransform);
        modelToView.preConcatenate(toViewScale);
        modelToView.preConcatenate(toViewLocation);
        //
        //            if (orientation == PlotOrientation.HORIZONTAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewY,
        //                        viewX);
        //            } else if (orientation == PlotOrientation.VERTICAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewX,
        //                        viewY);
        //            }
        FlatteningPathIterator iter = new FlatteningPathIterator(modelToView.createTransformedShape(entity)
                .getPathIterator(AffineTransform.getTranslateInstance(0, 0)), 5);
        Path2D.Float path = new Path2D.Float();
        path.append(iter, false);

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.fill(path);
        if (stroke != null) {
            g2.setColor(stroke);
            g2.draw(path);
        }
        g2.setComposite(comp);
        g2.setColor(c);
        g2.setClip(savedClip);
    } else {
        Logger.getLogger(getClass().getName()).info("Entity is null!");
    }
}

From source file:edu.uci.ics.jung.visualization.picking.ShapePickSupport.java

/** 
  * Iterates over Vertices, checking to see if x,y is contained in the
  * Vertex's Shape. If (x,y) is contained in more than one vertex, use
  * the vertex whose center is closest to the pick point.
  * @see edu.uci.ics.jung.visualization.picking.PickSupport#getVertex(double, double)
  *///  w  w  w  .  j a v a2  s .  com
public V getVertex(Layout<V, E> layout, double x, double y) {

    V closest = null;
    double minDistance = Double.MAX_VALUE;
    Point2D ip = vv.getRenderContext().getMultiLayerTransformer().inverseTransform(Layer.VIEW,
            new Point2D.Double(x, y));
    x = ip.getX();
    y = ip.getY();

    while (true) {
        try {
            for (V v : getFilteredVertices(layout)) {

                Shape shape = vv.getRenderContext().getVertexShapeTransformer().transform(v);
                // get the vertex location
                Point2D p = layout.transform(v);
                if (p == null)
                    continue;
                // transform the vertex location to screen coords
                p = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p);

                double ox = x - p.getX();
                double oy = y - p.getY();

                if (shape.contains(ox, oy)) {

                    if (style == Style.LOWEST) {
                        // return the first match
                        return v;
                    } else if (style == Style.HIGHEST) {
                        // will return the last match
                        closest = v;
                    } else {

                        // return the vertex closest to the
                        // center of a vertex shape
                        Rectangle2D bounds = shape.getBounds2D();
                        double dx = bounds.getCenterX() - ox;
                        double dy = bounds.getCenterY() - oy;
                        double dist = dx * dx + dy * dy;
                        if (dist < minDistance) {
                            minDistance = dist;
                            closest = v;
                        }
                    }
                }
            }
            break;
        } catch (ConcurrentModificationException cme) {
        }
    }
    return closest;
}

From source file:KIDLYRenderer.java

/**
 * Draws an item label.  This method is overridden so that the bar can be
 * used to calculate the label anchor point.
 *
 * @param g2  the graphics device.// w w  w .j  a  va2s .c  o m
 * @param data  the dataset.
 * @param row  the row.
 * @param column  the column.
 * @param plot  the plot.
 * @param generator  the label generator.
 * @param bar  the bar.
 * @param negative  a flag indicating a negative value.
 */
protected void drawItemLabel(Graphics2D g2, CategoryDataset data, int row, int column, CategoryPlot plot,
        CategoryItemLabelGenerator generator, Rectangle2D bar, boolean negative) {

    String label = generator.generateLabel(data, row, column);
    if (label == null) {
        return; // nothing to do
    }

    Font labelFont = getItemLabelFont(row, column);
    g2.setFont(labelFont);
    Paint paint = getItemLabelPaint(row, column);
    g2.setPaint(paint);

    // find out where to place the label...
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(row, column);
    } else {
        position = getNegativeItemLabelPosition(row, column);
    }

    // work out the label anchor point...
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar, plot.getOrientation());

    if (isInternalAnchor(position.getItemLabelAnchor())) {
        Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(),
                (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                position.getRotationAnchor());

        if (bounds != null) {
            if (!bar.contains(bounds.getBounds2D())) {
                if (!negative) {
                    position = getPositiveItemLabelPositionFallback();
                } else {
                    position = getNegativeItemLabelPositionFallback();
                }
                if (position != null) {
                    anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                            plot.getOrientation());
                }
            }
        }

    }

    if (position != null) {
        TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(),
                position.getTextAnchor(), position.getAngle(), position.getRotationAnchor());
    }
}

From source file:org.jfree.experimental.swt.SWTGraphics2D.java

/**
 * Returns <code>true</code> if the rectangle (in device space) intersects
 * with the shape (the interior, if <code>onStroke</code> is false, 
 * otherwise the stroked outline of the shape).
 * /*from   w  w  w .  jav a 2s .com*/
 * @param rect  a rectangle (in device space).
 * @param s the shape.
 * @param onStroke  test the stroked outline only?
 * 
 * @return A boolean. 
 */
@Override
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
    AffineTransform transform = getTransform();
    Shape ts;
    if (onStroke) {
        Stroke stroke = getStroke();
        ts = transform.createTransformedShape(stroke.createStrokedShape(s));
    } else {
        ts = transform.createTransformedShape(s);
    }
    if (!rect.getBounds2D().intersects(ts.getBounds2D())) {
        return false;
    }
    Area a1 = new Area(rect);
    Area a2 = new Area(ts);
    a1.intersect(a2);
    return !a1.isEmpty();
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Draws the edge <code>e</code>, whose endpoints are at <code>(x1,y1)</code>
 * and <code>(x2,y2)</code>, on the graphics context <code>g</code>.
 * The <code>Shape</code> provided by the <code>EdgeShapeFunction</code> instance
 * is scaled in the x-direction so that its width is equal to the distance between
 * <code>(x1,y1)</code> and <code>(x2,y2)</code>.
 *//* w w w .j a v  a2  s.co  m*/
protected void drawSimpleEdge(Graphics2D g, Edge e, int x1, int y1, int x2, int y2) {
    Pair endpoints = e.getEndpoints();
    Vertex v1 = (Vertex) endpoints.getFirst();
    Vertex v2 = (Vertex) endpoints.getSecond();
    boolean isLoop = v1.equals(v2);
    Shape s2 = vertexShapeFunction.getShape(v2);
    Shape edgeShape = edgeShapeFunction.getShape(e);

    boolean edgeHit = true;
    boolean arrowHit = true;
    Rectangle deviceRectangle = null;
    if (screenDevice != null) {
        Dimension d = screenDevice.getSize();
        if (d.width <= 0 || d.height <= 0) {
            d = screenDevice.getPreferredSize();
        }
        deviceRectangle = new Rectangle(0, 0, d.width, d.height);
    }

    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);

    if (isLoop) {
        // this is a self-loop. scale it is larger than the vertex
        // it decorates and translate it so that its nadir is
        // at the center of the vertex.
        Rectangle2D s2Bounds = s2.getBounds2D();
        xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight());
        xform.translate(0, -edgeShape.getBounds2D().getWidth() / 2);
    } else {
        // this is a normal edge. Rotate it to the angle between
        // vertex endpoints, then scale it to the distance between
        // the vertices
        float dx = x2 - x1;
        float dy = y2 - y1;
        float thetaRadians = (float) Math.atan2(dy, dx);
        xform.rotate(thetaRadians);
        float dist = (float) Math.sqrt(dx * dx + dy * dy);
        xform.scale(dist, 1.0);
    }

    edgeShape = xform.createTransformedShape(edgeShape);

    edgeHit = viewTransformer.transform(edgeShape).intersects(deviceRectangle);

    if (edgeHit == true) {

        Paint oldPaint = g.getPaint();

        // get Paints for filling and drawing
        // (filling is done first so that drawing and label use same Paint)
        Paint fill_paint = edgePaintFunction.getFillPaint(e);
        if (fill_paint != null) {
            g.setPaint(fill_paint);
            g.fill(edgeShape);
        }
        Paint draw_paint = edgePaintFunction.getDrawPaint(e);
        if (draw_paint != null) {
            g.setPaint(draw_paint);
            g.draw(edgeShape);
        }

        float scalex = (float) g.getTransform().getScaleX();
        float scaley = (float) g.getTransform().getScaleY();
        // see if arrows are too small to bother drawing
        if (scalex < .3 || scaley < .3)
            return;

        if (edgeArrowPredicate.evaluate(e)) {

            Shape destVertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getSecond());
            AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
            destVertexShape = xf.createTransformedShape(destVertexShape);

            arrowHit = viewTransformer.transform(destVertexShape).intersects(deviceRectangle);
            if (arrowHit) {

                AffineTransform at;
                if (edgeShape instanceof GeneralPath)
                    at = getArrowTransform((GeneralPath) edgeShape, destVertexShape);
                else
                    at = getArrowTransform(new GeneralPath(edgeShape), destVertexShape);
                if (at == null)
                    return;
                Shape arrow = edgeArrowFunction.getArrow(e);
                arrow = at.createTransformedShape(arrow);
                // note that arrows implicitly use the edge's draw paint
                g.fill(arrow);
            }
            if (e instanceof UndirectedEdge) {
                Shape vertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getFirst());
                xf = AffineTransform.getTranslateInstance(x1, y1);
                vertexShape = xf.createTransformedShape(vertexShape);

                arrowHit = viewTransformer.transform(vertexShape).intersects(deviceRectangle);

                if (arrowHit) {
                    AffineTransform at;
                    if (edgeShape instanceof GeneralPath)
                        at = getReverseArrowTransform((GeneralPath) edgeShape, vertexShape, !isLoop);
                    else
                        at = getReverseArrowTransform(new GeneralPath(edgeShape), vertexShape, !isLoop);
                    if (at == null)
                        return;
                    Shape arrow = edgeArrowFunction.getArrow(e);
                    arrow = at.createTransformedShape(arrow);
                    g.fill(arrow);
                }
            }
        }
        // use existing paint for text if no draw paint specified
        if (draw_paint == null)
            g.setPaint(oldPaint);
        String label = edgeStringer.getLabel(e);
        if (label != null) {
            labelEdge(g, e, label, x1, x2, y1, y2);
        }

        // restore old paint
        g.setPaint(oldPaint);
    }
}

From source file:nl.b3p.imagetool.ImageTool.java

private static Point calculateCenter(Shape shape, int srid, Bbox bbox, int width, int height) throws Exception {
    Point centerPoint = new Point();
    double x = shape.getBounds2D().getCenterX();
    double y = shape.getBounds2D().getCenterY();
    centerPoint.setLocation(x, y);//from w w  w.  j av  a  2s  .  c  o  m
    centerPoint = transformToScreen(centerPoint, srid, bbox, width, height);
    return centerPoint;
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

public void init() {
    boolean emptyBackground = true;
    if (config.isUseImageBackground() && background != null) {
        ByteArrayInputStream is = new ByteArrayInputStream(background);
        JPEGImgDecoder decoder = new DefaultJPEGImgDecoder();
        try {//from  www  . ja  v  a  2 s  .com
            this.image = decoder.decodeAsBufferedImage(is);
            this.width = image.getWidth();
            this.height = image.getHeight();
            emptyBackground = false;
        } catch (Exception e) {
            emptyBackground = true;
        }
    }
    if (emptyBackground) {
        this.width = config.getTextMarginLeft() * 2;
        this.height = config.getTextMarginBottom() * 6;
    }
    char[] chars = challengeId.toCharArray();
    charAttsList = new ArrayList();
    TextLayout text = null;
    AffineTransform textAt = null;
    String[] fontNames = config.getFontNames();
    for (int i = 0; i < chars.length; i++) {
        // font name
        String fontName = (fontNames.length == 1) ? fontNames[0] : fontNames[randomInt(0, fontNames.length)];

        // rise
        int rise = config.getTextRiseRange();
        if (rise > 0) {
            rise = randomInt(config.getTextMarginBottom(),
                    config.getTextMarginBottom() + config.getTextRiseRange());
        }

        if (config.getTextShear() > 0.0 || config.getTextRotation() > 0) {
            // rotation
            double dRotation = 0.0;
            if (config.getTextRotation() > 0) {
                dRotation = Math.toRadians(randomInt(-(config.getTextRotation()), config.getTextRotation()));
            }

            // shear
            double shearX = 0.0;
            double shearY = 0.0;
            if (config.getTextShear() > 0.0) {
                Random ran = new Random();
                shearX = ran.nextDouble() * config.getTextShear();
                shearY = ran.nextDouble() * config.getTextShear();
            }
            CharAttributes cf = new CharAttributes(chars[i], fontName, dRotation, rise, shearX, shearY);
            charAttsList.add(cf);
            text = new TextLayout(chars[i] + "", getFont(fontName),
                    new FontRenderContext(null, config.isFontAntialiasing(), false));
            textAt = new AffineTransform();
            if (config.getTextRotation() > 0)
                textAt.rotate(dRotation);
            if (config.getTextShear() > 0.0)
                textAt.shear(shearX, shearY);
        } else {
            CharAttributes cf = new CharAttributes(chars[i], fontName, 0, rise, 0.0, 0.0);
            charAttsList.add(cf);
        }
        if (emptyBackground) {
            Shape shape = text.getOutline(textAt);
            //                this.width += text.getBounds().getWidth();
            this.width += (int) shape.getBounds2D().getWidth();
            this.width += config.getTextSpacing() + 1;
            if (this.height < (int) shape.getBounds2D().getHeight() + rise) {
                this.height = (int) shape.getBounds2D().getHeight() + rise;
            }
        }
    }
    if (emptyBackground) {
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gfx = (Graphics2D) this.image.getGraphics();
        gfx.setBackground(Color.WHITE);
        gfx.clearRect(0, 0, width, height);
    }
}