Example usage for java.awt.geom Area Area

List of usage examples for java.awt.geom Area Area

Introduction

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

Prototype

public Area(Shape s) 

Source Link

Document

The Area class creates an area geometry from the specified Shape object.

Usage

From source file:Pear.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension d = getSize();//from  w w  w .  j  a v  a2  s  .c  o  m
    int w = d.width;
    int h = d.height;
    double ew = w / 2;
    double eh = h / 2;

    g2.setColor(Color.green);

    // Creates the first leaf by filling the intersection of two Area objects
    // created from an ellipse.
    leaf.setFrame(ew - 16, eh - 29, 15.0, 15.0);
    leaf1 = new Area(leaf);
    leaf.setFrame(ew - 14, eh - 47, 30.0, 30.0);
    leaf2 = new Area(leaf);
    leaf1.intersect(leaf2);
    g2.fill(leaf1);

    // Creates the second leaf.
    leaf.setFrame(ew + 1, eh - 29, 15.0, 15.0);
    leaf1 = new Area(leaf);
    leaf2.intersect(leaf1);
    g2.fill(leaf2);

    g2.setColor(Color.black);

    // Creates the stem by filling the Area resulting from the subtraction of
    // two Area objects created from an ellipse.
    stem.setFrame(ew, eh - 42, 40.0, 40.0);
    st1 = new Area(stem);
    stem.setFrame(ew + 3, eh - 47, 50.0, 50.0);
    st2 = new Area(stem);
    st1.subtract(st2);
    g2.fill(st1);

    g2.setColor(Color.yellow);

    // Creates the pear itself by filling the Area resulting from the union of
    // two Area objects created by two different ellipses.
    circle.setFrame(ew - 25, eh, 50.0, 50.0);
    oval.setFrame(ew - 19, eh - 20, 40.0, 70.0);
    circ = new Area(circle);
    ov = new Area(oval);
    circ.add(ov);
    g2.fill(circ);
}

From source file:DrawShapes_2008.java

/**
 * Generates a donut shape from the given location and radii by subtracting
 * an inner circular Area from an outer one.
 *///w  ww  . j a va  2 s .  c o m
private static Shape generateDonut(double x, double y, double innerRadius, double outerRadius) {
    Area a1 = new Area(new Ellipse2D.Double(x, y, outerRadius, outerRadius));
    double innerOffset = (outerRadius - innerRadius) / 2;
    Area a2 = new Area(new Ellipse2D.Double(x + innerOffset, y + innerOffset, innerRadius, innerRadius));
    a1.subtract(a2);
    return a1;
}

From source file:it.unibo.alchemist.model.implementations.linkingrules.ConnectionBeam.java

@Override
public Neighborhood<T> computeNeighborhood(final Node<T> center, final Environment<T> env) {
    final Neighborhood<T> normal = super.computeNeighborhood(center, env);
    if (oenv == null) {
        if (!(env instanceof Environment2DWithObstacles<?, ?>)) {
            return normal;
        }/* w  w w  . ja va 2 s.  com*/
        oenv = (Environment2DWithObstacles<?, ?>) env;
        obstacles.reset();
        oenv.getObstacles().forEach((obs) -> {
            /*
             * Doubles are prone to approximation errors. Use nextAfter to get rid of them
             */
            final Rectangle2D bounds = obs.getBounds2D();
            final double mx = nextAfter(bounds.getMinX(), java.lang.Double.NEGATIVE_INFINITY);
            final double my = nextAfter(bounds.getMinY(), java.lang.Double.NEGATIVE_INFINITY);
            final double ex = nextUp(bounds.getMaxX());
            final double ey = nextUp(bounds.getMaxY());
            obstacles.add(new Area(new Rectangle2D.Double(mx, my, ex - mx, ey - my)));
        });
    }
    if (!normal.isEmpty()) {
        final Position cp = env.getPosition(center);
        final List<Node<T>> neighs = normal.getNeighbors().stream().filter((neigh) -> {
            final Position np = env.getPosition(neigh);
            return !oenv.intersectsObstacle(cp, np) || projectedBeamOvercomesObstacle(cp, np);
        }).collect(ArrayList::new, (l, el) -> l.add(el), (l1, l2) -> l1.addAll(l2));
        return Neighborhoods.make(env, center, neighs);
    }
    return normal;
}

From source file:TArea.java

public void actionPerformed(ActionEvent e) {
    JRadioButton temp = (JRadioButton) e.getSource();

    if (temp.equals(addButton)) {
        canvas.area1 = new Area(canvas.gp);
        canvas.area1.add(canvas.area2);/*from  w ww.ja  v  a2 s . c o m*/
        canvas.drawFlag = false;
        canvas.fillFlag = true;
        canvas.repaint();
    } else if (temp.equals(subtractButton)) {
        canvas.area1 = new Area(canvas.gp);
        canvas.area1.subtract(canvas.area2);
        canvas.drawFlag = false;
        canvas.fillFlag = true;
        canvas.repaint();
    } else if (temp.equals(intersectButton)) {
        canvas.area1 = new Area(canvas.gp);
        canvas.area1.intersect(canvas.area2);
        canvas.drawFlag = false;
        canvas.fillFlag = true;
        canvas.repaint();
    } else if (temp.equals(exclusiveORButton)) {
        canvas.area1 = new Area(canvas.gp);
        canvas.area1.exclusiveOr(canvas.area2);
        canvas.drawFlag = false;
        canvas.fillFlag = true;
        canvas.repaint();
    } else if (temp.equals(resetButton)) {
        if (canvas.drawFlag == false) {
            canvas.area1 = new Area(canvas.gp);
            canvas.drawFlag = true;
            canvas.fillFlag = false;
            canvas.repaint();
        }
    }
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.JFreeChartReportDrawable.java

public void draw(final Graphics2D graphics2D, final Rectangle2D bounds) {
    this.bounds = (Rectangle2D) bounds.clone();
    if (chartRenderingInfo != null) {
        this.chartRenderingInfo.clear();
    }//from w ww . j  a  va 2s.  c o  m
    final Graphics2D g2 = (Graphics2D) graphics2D.create();
    this.chart.draw(g2, bounds, chartRenderingInfo);
    g2.dispose();

    if (chartRenderingInfo == null || debugRendering == false) {
        return;
    }

    graphics2D.setColor(Color.RED);
    final Rectangle2D dataArea = getDataAreaOffset();
    final EntityCollection entityCollection = chartRenderingInfo.getEntityCollection();
    for (int i = 0; i < entityCollection.getEntityCount(); i++) {
        final ChartEntity chartEntity = entityCollection.getEntity(i);
        if (chartEntity instanceof XYItemEntity || chartEntity instanceof CategoryItemEntity
                || chartEntity instanceof PieSectionEntity) {
            final Area a = new Area(chartEntity.getArea());
            if (buggyDrawArea) {
                a.transform(AffineTransform.getTranslateInstance(dataArea.getX(), dataArea.getY()));
            }
            a.intersect(new Area(dataArea));
            graphics2D.draw(a);
        } else {
            graphics2D.draw(chartEntity.getArea());
        }
    }
}

From source file:it.unibo.alchemist.model.implementations.linkingrules.ConnectionBeam.java

private boolean projectedBeamOvercomesObstacle(final Position pos1, final Position pos2) {
    final double p1x = pos1.getCoordinate(0);
    final double p1y = pos1.getCoordinate(1);
    final double p2x = pos2.getCoordinate(0);
    final double p2y = pos2.getCoordinate(1);
    final double x = p2x - p1x;
    final double y = p2y - p1y;
    /*/*from   www.  j ava2 s .  com*/
     * Compute the angle
     */
    final double angle = atan2(y, x);
    /*
     * Deduce surrounding beam vertices
     */
    final double dx = range * cos(PI / 2 + angle);
    final double dy = range * sin(PI / 2 + angle);
    /*
     * Enlarge the beam
     */
    final double cx = range * cos(angle);
    final double cy = range * sin(angle);
    /*
     * Create the beam
     */
    final Path2D.Double beamShape = new Path2D.Double();
    beamShape.moveTo(p1x + dx - cx, p1y + dy - cy);
    beamShape.lineTo(p1x - dx - cx, p1y - dy - cy);
    beamShape.lineTo(p2x - dx + cx, p2y - dy + cy);
    beamShape.lineTo(p2x + dx + cx, p2y + dy + cy);
    beamShape.closePath();
    final Area beam = new Area(beamShape);
    /*
     * Perform subtraction
     */
    beam.subtract(obstacles);
    /*
     * Rebuild single areas
     */
    final List<Path2D.Double> subareas = new ArrayList<>();
    Path2D.Double curpath = new Path2D.Double();
    final PathIterator pi = beam.getPathIterator(null);
    final double[] coords = new double[COORDS];
    while (!pi.isDone()) {
        switch (pi.currentSegment(coords)) {
        case PathIterator.SEG_MOVETO:
            curpath = new Path2D.Double();
            curpath.moveTo(coords[0], coords[1]);
            break;
        case PathIterator.SEG_LINETO:
            curpath.lineTo(coords[0], coords[1]);
            break;
        case PathIterator.SEG_CLOSE:
            curpath.closePath();
            subareas.add(curpath);
            break;
        default:
            throw new IllegalArgumentException();
        }
        pi.next();
    }
    /*
     * At least one area must contain both points
     */
    for (final Path2D.Double p : subareas) {
        if (p.contains(p1x, p1y) && p.contains(p2x, p2y)) {
            return true;
        }
    }
    return false;
}

From source file:no.oddsor.simulator3.json.SensorReader.java

public Collection<Sensor> getSensors() {
    Collection<Sensor> sensors = new ArrayList<>();
    if (object == null)
        return sensors;

    JSONArray sensorList = (JSONArray) object.get("Sensors");
    for (Object sensorOb : sensorList) {
        JSONObject sensorObject = (JSONObject) sensorOb;
        Sensor sensor = null;//www.j  av  a  2 s  .c om
        String type = (String) sensorObject.get("Type");
        String name = (String) sensorObject.get("Name");
        JSONArray locationArray = (JSONArray) sensorObject.get("Position");
        Point location = null;
        if (locationArray != null) {
            location = new Point(Integer.parseInt(locationArray.get(0).toString()),
                    Integer.parseInt(locationArray.get(1).toString()));
        }
        switch (type) {
        case "Contact":
            String attached = (String) sensorObject.get("Attached_to");
            sensor = new Contact(name, attached);
            break;
        case "Camera":
            JSONArray range = (JSONArray) sensorObject.get("Range");
            double[] dArray = new double[range.size()];
            for (int i = 0; i < dArray.length; i++) {
                dArray[i] = Double.parseDouble(range.get(i).toString());
            }
            if (!sensorObject.containsKey("Resolution"))
                sensor = new Camera(name, location,
                        Double.parseDouble(sensorObject.get("Direction").toString()),
                        Double.parseDouble(sensorObject.get("FieldOfView").toString()), dArray);
            else
                sensor = new Camera(name, location,
                        Double.parseDouble(sensorObject.get("Direction").toString()),
                        Double.parseDouble(sensorObject.get("FieldOfView").toString()), dArray,
                        Integer.parseInt(sensorObject.get("Resolution").toString()));
            break;
        case "Door":
            JSONArray dimensionArray = (JSONArray) sensorObject.get("Size");
            Dimension dims = new Dimension(Integer.parseInt(dimensionArray.get(0).toString()),
                    Integer.parseInt(dimensionArray.get(1).toString()));
            sensor = new Door(name, location, dims);
            break;
        case "MotionSensor":
            if (sensorObject.containsKey("Radius"))
                sensor = new MotionSensor(name, location,
                        Double.parseDouble(sensorObject.get("Radius").toString()));
            else {
                sensor = new MotionSensor(name, location,
                        Double.parseDouble(sensorObject.get("Direction").toString()),
                        Double.parseDouble(sensorObject.get("Range").toString()),
                        Double.parseDouble(sensorObject.get("FieldOfView").toString()));
            }
        }
        if (sensorObject.containsKey("Exclude")) {
            JSONArray excludeArray = (JSONArray) sensorObject.get("Exclude");
            for (Object exclude : excludeArray) {
                JSONObject exclud = (JSONObject) exclude;
                JSONArray edgeArray = (JSONArray) exclud.get("Edge");
                Point edgeLocation = new Point(Integer.parseInt(edgeArray.get(0).toString()),
                        Integer.parseInt(edgeArray.get(1).toString()));
                String direction = (String) exclud.get("Direction");
                Point edge = null;
                Dimension dim = new Dimension(1000, 1000);
                switch (direction) {
                case ("Northeast"):
                    edge = new Point(edgeLocation.x, edgeLocation.y - 1000);
                    break;
                case ("Northwest"):
                    edge = new Point(edgeLocation.x - 1000, edgeLocation.y - 1000);
                    break;
                case ("Southeast"):
                    edge = new Point(edgeLocation.x, edgeLocation.y);
                    break;
                case ("Southwest"):
                    edge = new Point(edgeLocation.x - 1000, edgeLocation.y);
                }
                Rectangle exluTangle = new Rectangle(edge, dim);
                sensor.removeArea(new Area(exluTangle));
            }
        }
        if (sensorObject.containsKey("Confine")) {
            JSONArray coords = (JSONArray) sensorObject.get("Confine");
            int[] x = new int[coords.size()];
            int[] y = new int[coords.size()];
            for (int i = 0; i < coords.size(); i++) {
                JSONArray coord = (JSONArray) coords.get(i);
                x[i] = Integer.parseInt(coord.get(0).toString());
                y[i] = Integer.parseInt(coord.get(1).toString());
            }
            Polygon p = new Polygon(x, y, coords.size());
            Area excluPoly = new Area(p);
            sensor.confineToArea(excluPoly);
        }
        sensors.add(sensor);
    }

    return sensors;
}

From source file:org.zephyrsoft.sdb2.presenter.SongView.java

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    int topBorderHeight = topMargin;
    int bottomBorderHeight = bottomMargin;

    // gradient upper border as overlay
    Area areaUpper = new Area(new Rectangle2D.Double(0, 0, getWidth(), topBorderHeight));
    g2d.setPaint(new GradientPaint(0, 0,
            new Color(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), 255), 0,
            topBorderHeight,/*from  w w w.  j ava  2 s.  c  o  m*/
            new Color(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), 0),
            false));
    g2d.fill(areaUpper);

    // gradient lower border as overlay
    Area areaLower = new Area(
            new Rectangle2D.Double(0, getHeight() - bottomBorderHeight, getWidth(), getHeight()));
    g2d.setPaint(new GradientPaint(0, getHeight() - bottomBorderHeight,
            new Color(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), 0), 0,
            getHeight(),
            new Color(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), 255),
            false));
    g2d.fill(areaLower);
}

From source file:CompositeEffects.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;

    // fill the background
    g.setPaint(new Color(175, 175, 175));
    g.fillRect(0, 0, getWidth(), getHeight());

    // Set text attributes
    g.setColor(Color.black);//from   w w w  .j  ava2 s .c  o m
    g.setFont(new Font("SansSerif", Font.BOLD, 12));

    // Draw the unmodified image
    g.translate(10, 10);
    g.drawImage(cover, 0, 0, this);
    g.drawString("SRC_OVER", 0, COVERHEIGHT + 15);

    // Draw the cover again, using AlphaComposite to make the opaque
    // colors of the image 50% translucent
    g.translate(COVERWIDTH + 10, 0);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g.drawImage(cover, 0, 0, this);

    // Restore the pre-defined default Composite for the screen, so
    // opaque colors stay opaque.
    g.setComposite(AlphaComposite.SrcOver);
    // Label the effect
    g.drawString("SRC_OVER, 50%", 0, COVERHEIGHT + 15);

    // Now get an offscreen image to work with. In order to achieve
    // certain compositing effects, the drawing surface must support
    // transparency. Onscreen drawing surfaces cannot, so we have to do the
    // compositing in an offscreen image that is specially created to have
    // an "alpha channel", then copy the final result to the screen.
    BufferedImage offscreen = new BufferedImage(COVERWIDTH, COVERHEIGHT, BufferedImage.TYPE_INT_ARGB);

    // First, fill the image with a color gradient background that varies
    // left-to-right from opaque to transparent yellow
    Graphics2D osg = offscreen.createGraphics();
    osg.setPaint(new GradientPaint(0, 0, Color.yellow, COVERWIDTH, 0, new Color(255, 255, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now copy the cover image on top of this, but use the DstOver rule
    // which draws it "underneath" the existing pixels, and allows the
    // image to show depending on the transparency of those pixels.
    osg.setComposite(AlphaComposite.DstOver);
    osg.drawImage(cover, 0, 0, this);

    // And display this composited image on the screen. Note that the
    // image is opaque and that none of the screen background shows through
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("DST_OVER", 0, COVERHEIGHT + 15);

    // Now start over and do a new effect with the off-screen image.
    // First, fill the offscreen image with a new color gradient. We
    // don't care about the colors themselves; we just want the
    // translucency of the background to vary. We use opaque black to
    // transparent black. Note that since we've already used this offscreen
    // image, we set the composite to Src, we can fill the image and
    // ignore anything that is already there.
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now set the compositing type to SrcIn, so colors come from the
    // source, but translucency comes from the destination
    osg.setComposite(AlphaComposite.SrcIn);

    // Draw our loaded image into the off-screen image, compositing it.
    osg.drawImage(cover, 0, 0, this);

    // And then copy our off-screen image to the screen. Note that the
    // image is translucent and some of the image shows through.
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_IN", 0, COVERHEIGHT + 15);

    // If we do the same thing but use SrcOut, then the resulting image
    // will have the inverted translucency values of the destination
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);
    osg.setComposite(AlphaComposite.SrcOut);
    osg.drawImage(cover, 0, 0, this);
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_OUT", 0, COVERHEIGHT + 15);

    // Here's a cool effect; it has nothing to do with compositing, but
    // uses an arbitrary shape to clip the image. It uses Area to combine
    // shapes into more complicated ones.
    g.translate(COVERWIDTH + 10, 0);
    Shape savedClip = g.getClip(); // Save current clipping region
    // Create a shape to use as the new clipping region.
    // Begin with an ellipse
    Area clip = new Area(new Ellipse2D.Float(0, 0, COVERWIDTH, COVERHEIGHT));
    // Intersect with a rectangle, truncating the ellipse.
    clip.intersect(new Area(new Rectangle(5, 5, COVERWIDTH - 10, COVERHEIGHT - 10)));
    // Then subtract an ellipse from the bottom of the truncated ellipse.
    clip.subtract(new Area(new Ellipse2D.Float(COVERWIDTH / 2 - 40, COVERHEIGHT - 20, 80, 40)));
    // Use the resulting shape as the new clipping region
    g.clip(clip);
    // Then draw the image through this clipping region
    g.drawImage(cover, 0, 0, this);
    // Restore the old clipping region so we can label the effect
    g.setClip(savedClip);
    g.drawString("Clipping", 0, COVERHEIGHT + 15);
}

From source file:net.technicpack.launcher.lang.ResourceLoader.java

public BufferedImage getCircleClippedImage(String imageName) {
    BufferedImage contentImage = getImage(imageName);

    // copy the picture to an image with transparency capabilities
    BufferedImage outputImage = new BufferedImage(contentImage.getWidth(), contentImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) outputImage.getGraphics();
    g2.drawImage(contentImage, 0, 0, null);

    // Create the area around the circle to cut out
    Area cutOutArea = new Area(new Rectangle(0, 0, outputImage.getWidth(), outputImage.getHeight()));

    int diameter = (outputImage.getWidth() < outputImage.getHeight()) ? outputImage.getWidth()
            : outputImage.getHeight();/*ww  w  .j  a  v  a2s .co m*/
    cutOutArea.subtract(new Area(new Ellipse2D.Float((outputImage.getWidth() - diameter) / 2,
            (outputImage.getHeight() - diameter) / 2, diameter, diameter)));

    // Set the fill color to an opaque color
    g2.setColor(Color.WHITE);
    // Set the composite to clear pixels
    g2.setComposite(AlphaComposite.Clear);
    // Turn on antialiasing
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Clear the cut out area
    g2.fill(cutOutArea);

    // dispose of the graphics object
    g2.dispose();

    return outputImage;
}