Example usage for java.awt.geom Area intersect

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

Introduction

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

Prototype

public void intersect(Area rhs) 

Source Link

Document

Sets the shape of this Area to the intersection of its current shape and the shape of the specified Area .

Usage

From source file:BasicShapes.java

public static void main(String[] args) {
    Area shape = new Area(new Rectangle(1, 1, 1, 1));
    shape.add(new Area(new Rectangle(1, 1, 1, 1)));
    shape.subtract(new Area(new Rectangle(1, 1, 1, 1)));
    shape.intersect(new Area(new Rectangle(1, 1, 1, 1)));
    shape.exclusiveOr(new Area(new Rectangle(1, 1, 1, 1)));
}

From source file:Main.java

public static void main(String[] args) {
    Area shape = new Area(new Rectangle(1, 1, 1, 1));
    shape.add(new Area(new Rectangle(1, 1, 1, 1)));
    shape.subtract(new Area(new Rectangle(1, 1, 1, 1)));
    shape.intersect(new Area(new Rectangle(1, 1, 1, 1)));
    shape.exclusiveOr(new Area(new Rectangle(1, 1, 1, 1)));

    System.out.println(shape.intersects(new Rectangle(1, 1, 1, 1)));
}

From source file:G2DCircleIntersectPDF.java

public static void main(String[] args) {
    Document document = new Document();
    try {// ww  w .j  a v  a 2s .  c om
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("G2DCircleIntersectPDF.pdf"));
        document.open();
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\windows\\fonts");

        int w = 150;
        int h = 150;
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h, mapper);
        tp.setWidth(w);
        tp.setHeight(h);
        double ew = w / 2;
        double eh = h / 2;
        Ellipse2D.Double circle, circle1;

        circle = new Ellipse2D.Double(ew - 16, eh - 29, 50.0, 50.0);

        g2.setColor(Color.green);
        g2.fill(circle);

        g2.setColor(Color.red);
        circle1 = new Ellipse2D.Double(ew, eh, 50.0, 50.0);
        g2.fill(circle1);

        Area area1 = new Area(circle);
        Area area2 = new Area(circle1);

        g2.setColor(Color.BLUE);
        area1.intersect(area2);
        g2.fill(area1);

        g2.dispose();
        cb.addTemplate(tp, 50, 400);

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    document.close();
}

From source file:ShapeTransform.java

/**
 * Clips the given shape to the given bounds. If the shape is a Line2D, manual
 * clipping is performed, as the built in Area does not handle lines.
 * //from  ww  w. j  a v a 2s.  c o  m
 * @param s
 *          the shape to be clipped
 * @param bounds
 *          the bounds to which the shape should be clipped
 * @return the clipped shape.
 */
public static Shape performCliping(final Shape s, final Rectangle2D bounds) {
    if (s instanceof Line2D) {
        final Line2D line = (Line2D) s;
        final Point2D[] clipped = getClipped(line.getX1(), line.getY1(), line.getX2(), line.getY2(), -DELTA,
                DELTA + bounds.getWidth(), -DELTA, DELTA + bounds.getHeight());
        if (clipped == null) {
            return new GeneralPath();
        }
        return new Line2D.Float(clipped[0], clipped[1]);
    }

    final Rectangle2D boundsCorrected = bounds.getBounds2D();
    boundsCorrected.setRect(-DELTA, -DELTA, DELTA + boundsCorrected.getWidth(),
            DELTA + boundsCorrected.getHeight());
    final Area a = new Area(boundsCorrected);
    if (a.isEmpty()) {
        // don't clip ... Area does not like lines
        // operations with lines always result in an empty Bounds:(0,0,0,0) area
        return new GeneralPath();
    }

    final Area clipArea = new Area(s);
    a.intersect(clipArea);
    return a;

}

From source file:MainClass.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    Ellipse2D e1 = new Ellipse2D.Double(20.0, 20.0, 80.0, 70.0);
    Ellipse2D e2 = new Ellipse2D.Double(20.0, 70.0, 40.0, 40.0);

    Area a1 = new Area(e1);
    Area a2 = new Area(e2);

    a1.intersect(a2);

    g2.setColor(Color.orange);//from  w w  w. j ava2 s.c  o  m
    g2.fill(a1);

    g2.setColor(Color.black);
    g2.drawString("intersect", 20, 140);
}

From source file:net.sf.maltcms.chromaui.charts.Chromatogram1DChartProvider.java

/**
 *
 * @param f//from   w w  w .  j a v a2s . c om
 * @param useScanAcquisitionTime
 * @param outline
 * @param fill
 * @param valueVar
 * @return
 */
public static List<XYAnnotation> generatePeakShapes(IFileFragment f, boolean useScanAcquisitionTime,
        Color outline, Color fill, String valueVar) {
    List<XYAnnotation> l = new ArrayList<>();
    try {
        IVariableFragment peakNames = f.getChild("peak_name");
        IVariableFragment peakRT = f.getChild("peak_retention_time");
        IVariableFragment peakStartRT = f.getChild("peak_start_time");
        IVariableFragment peakStopRT = f.getChild("peak_end_time");

        int peaks = peakRT.getArray().getShape()[0];

        boolean baselineAvailable = true;

        IVariableFragment blStartRT = null;
        IVariableFragment blStopRT = null;
        IVariableFragment blStartValue = null;
        IVariableFragment blStopValue = null;

        try {
            blStartRT = f.getChild("baseline_start_time");
            blStopRT = f.getChild("baseline_stop_time");
            blStartValue = f.getChild("baseline_start_value");
            blStopValue = f.getChild("baseline_stop_value");
        } catch (ResourceNotAvailableException e) {
            baselineAvailable = false;
        }

        boolean andichromMode = valueVar.equals("ordinate_values");

        Array ordinateValues = null;
        try {
            ordinateValues = f.getChild(valueVar).getArray();
        } catch (ResourceNotAvailableException rne) {
            ordinateValues = f.getChild("total_intensity").getArray();
            andichromMode = false;
        }

        Collection<String> peaknames = ArrayTools.getStringsFromArray(peakNames.getArray());
        IndexIterator ii = peakRT.getArray().getIndexIterator();

        Iterator<String> peaknamesIter = peaknames.iterator();

        for (int i = 0; i < peaks; i++) {
            double sat = ii.getDoubleNext();
            double peakStartTime = peakStartRT.getArray().getDouble(i);
            double peakStopTime = peakStopRT.getArray().getDouble(i);
            int scan = 0;
            int startIdx, stopIdx;
            if (andichromMode) {
                double delay = f.getChild("actual_delay_time").getArray().getDouble(0);
                double samplingRate = f.getChild("actual_sampling_interval").getArray().getDouble(0);
                scan = (int) (Math.floor(((sat - delay) / samplingRate)));
                startIdx = (int) (Math.floor(((peakStartTime - delay) / samplingRate)));
                stopIdx = (int) (Math.floor(((peakStopTime - delay) / samplingRate)));
            } else {
                Array satA = f.getChild("scan_acquisition_time").getArray();
                double[] d = (double[]) satA.get1DJavaArray(double.class);
                scan = Arrays.binarySearch(d, sat);
                if (scan < 0) {
                    scan = ((-1) * (scan + 1));
                }
                startIdx = Arrays.binarySearch(d, peakStartTime);
                stopIdx = Arrays.binarySearch(d, peakStopTime);
                if (startIdx < 0) {
                    startIdx = ((-1) * (startIdx + 1));
                }
                if (stopIdx < 0) {
                    stopIdx = ((-1) * (stopIdx + 1));
                }
            }
            String name = peaknamesIter.next();
            double blStartTime, blStopTime, blStartVal, blStopVal;
            if (baselineAvailable) {
                blStartTime = blStartRT.getArray().getDouble(i);
                blStopTime = blStopRT.getArray().getDouble(i);
                blStartVal = blStartValue.getArray().getDouble(i);
                blStopVal = blStopValue.getArray().getDouble(i);
            } else {
                blStartTime = peakStartTime;
                blStopTime = peakStopTime;
                blStartVal = ordinateValues.getDouble(startIdx);
                blStopVal = ordinateValues.getDouble(stopIdx);
            }

            if (name.trim().isEmpty()) {
                name = "NN";
            }

            GeneralPath gp = new GeneralPath();
            if (useScanAcquisitionTime) {
                Array sat2 = f.getChild("scan_acquisition_time").getArray();
                gp.moveTo(peakStartTime, ordinateValues.getDouble(startIdx));
                for (int j = startIdx + 1; j <= stopIdx + 1; j++) {
                    gp.lineTo(sat2.getDouble(j), ordinateValues.getDouble(j));
                }
                gp.lineTo(Math.max(blStopTime, peakStopTime), blStopVal);
                gp.lineTo(Math.min(blStartTime, peakStartTime), blStartVal);
                gp.closePath();
                //gp.closePath();
                Rectangle2D.Double bbox = new Rectangle2D.Double(peakStartTime, 0, peakStopTime - peakStartTime,
                        ordinateValues.getDouble(scan));
                Area a = new Area(bbox);
                a.intersect(new Area(gp));
                XYShapeAnnotation xypa = new XYShapeAnnotation(a, new BasicStroke(), outline, fill);
                XYLineAnnotation xyla = new XYLineAnnotation(blStartTime, blStartVal, blStopTime, blStopVal,
                        new BasicStroke(), Color.BLACK);
                l.add(xypa);
                l.add(xyla);
                //                    XYLineAnnotation baseline = new XYLineAnnotation();
            } else {
                gp.moveTo(startIdx, ordinateValues.getDouble(startIdx));
                for (int j = startIdx + 1; j <= stopIdx + 1; j++) {
                    gp.lineTo(j, ordinateValues.getDouble(j));
                }
                gp.closePath();
                XYShapeAnnotation xypa = new XYShapeAnnotation(gp, new BasicStroke(), outline, fill);
                l.add(xypa);
            }
        }
    } catch (ResourceNotAvailableException rnae) {
        Logger.getLogger(Chromatogram1DChartProvider.class.getName()).info(rnae.getLocalizedMessage());
    }
    return l;
}

From source file:CombiningShapes.java

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    String option = (String) mOptions.getSelectedItem();
    if (option.equals("outline")) {
        // draw the outlines and return.
        g2.draw(mShapeOne);//from  www. j  a  v a2 s .com
        g2.draw(mShapeTwo);
        return;
    }

    // Create Areas from the shapes.
    Area areaOne = new Area(mShapeOne);
    Area areaTwo = new Area(mShapeTwo);
    // Combine the Areas according to the selected option.
    if (option.equals("add"))
        areaOne.add(areaTwo);
    else if (option.equals("intersection"))
        areaOne.intersect(areaTwo);
    else if (option.equals("subtract"))
        areaOne.subtract(areaTwo);
    else if (option.equals("exclusive or"))
        areaOne.exclusiveOr(areaTwo);

    // Fill the resulting Area.
    g2.setPaint(Color.orange);
    g2.fill(areaOne);
    // Draw the outline of the resulting Area.
    g2.setPaint(Color.black);
    g2.draw(areaOne);
}

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 a  v  a2  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:chiliad.parser.pdf.extractor.vectorgraphics.operator.Invoke.java

/**
 * process : Do : Paint the specified XObject (section 4.7).
 *
 * @param operator The operator that is being executed.
 * @param arguments List/*from  w  w  w . ja  v a 2 s  . c  om*/
 * @throws IOException If there is an error invoking the sub object.
 */
@Override
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    VectorGraphicsExtractor extractor = (VectorGraphicsExtractor) context;

    PDPage page = extractor.getPage();
    COSName objectName = (COSName) arguments.get(0);
    Map<String, PDXObject> xobjects = extractor.getResources().getXObjects();
    PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
    if (xobject == null) {
        LOG.warn("Can't find the XObject for '" + objectName.getName() + "'");
    } else if (xobject instanceof PDXObjectImage) {
        PDXObjectImage image = (PDXObjectImage) xobject;
        try {
            if (image.getImageMask()) {
                // set the current non stroking colorstate, so that it can
                // be used to create a stencil masked image
                image.setStencilColor(extractor.getGraphicsState().getNonStrokingColor());
            }
            BufferedImage awtImage = image.getRGBImage();
            if (awtImage == null) {
                LOG.warn("getRGBImage returned NULL");
                return;//TODO PKOCH
            }
            int imageWidth = awtImage.getWidth();
            int imageHeight = awtImage.getHeight();
            double pageHeight = extractor.getPageSize().getHeight();

            LOG.debug("imageWidth: " + imageWidth + "\t\timageHeight: " + imageHeight);

            Matrix ctm = extractor.getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctm.getYScale();
            float angle = (float) Math.acos(ctm.getValue(0, 0) / ctm.getXScale());
            if (ctm.getValue(0, 1) < 0 && ctm.getValue(1, 0) > 0) {
                angle = (-1) * angle;
            }
            ctm.setValue(2, 1, (float) (pageHeight - ctm.getYPosition() - Math.cos(angle) * yScaling));
            ctm.setValue(2, 0, (float) (ctm.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctm.setValue(0, 1, (-1) * ctm.getValue(0, 1));
            ctm.setValue(1, 0, (-1) * ctm.getValue(1, 0));
            AffineTransform ctmAT = ctm.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);
            extractor.drawImage(awtImage, ctmAT);
        } catch (Exception e) {
            LOG.error(e, e);
        }
    } else if (xobject instanceof PDXObjectForm) {
        // save the graphics state
        context.getGraphicsStack().push((PDGraphicsState) context.getGraphicsState().clone());

        PDXObjectForm form = (PDXObjectForm) xobject;
        COSStream formContentstream = form.getCOSStream();
        // find some optional resources, instead of using the current resources
        PDResources pdResources = form.getResources();
        // if there is an optional form matrix, we have to map the form space to the user space
        Matrix matrix = form.getMatrix();
        if (matrix != null) {
            Matrix xobjectCTM = matrix.multiply(context.getGraphicsState().getCurrentTransformationMatrix());
            context.getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
        }
        if (form.getBBox() != null) {
            PDGraphicsState graphicsState = context.getGraphicsState();
            PDRectangle bBox = form.getBBox();

            float x1 = bBox.getLowerLeftX();
            float y1 = bBox.getLowerLeftY();
            float x2 = bBox.getUpperRightX();
            float y2 = bBox.getUpperRightY();

            Point2D p0 = extractor.transformedPoint(x1, y1);
            Point2D p1 = extractor.transformedPoint(x2, y1);
            Point2D p2 = extractor.transformedPoint(x2, y2);
            Point2D p3 = extractor.transformedPoint(x1, y2);

            GeneralPath bboxPath = new GeneralPath();
            bboxPath.moveTo((float) p0.getX(), (float) p0.getY());
            bboxPath.lineTo((float) p1.getX(), (float) p1.getY());
            bboxPath.lineTo((float) p2.getX(), (float) p2.getY());
            bboxPath.lineTo((float) p3.getX(), (float) p3.getY());
            bboxPath.closePath();

            Area resultClippingArea = new Area(graphicsState.getCurrentClippingPath());
            Area newArea = new Area(bboxPath);
            resultClippingArea.intersect(newArea);

            graphicsState.setCurrentClippingPath(resultClippingArea);
        }
        getContext().processSubStream(page, pdResources, formContentstream);

        // restore the graphics state
        context.setGraphicsState((PDGraphicsState) context.getGraphicsStack().pop());
    }
}

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 w w  .  ja  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());
        }
    }
}