Example usage for java.awt.geom Rectangle2D getX

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

Introduction

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

Prototype

public abstract double getX();

Source Link

Document

Returns the X coordinate of the upper-left corner of the framing rectangle in double precision.

Usage

From source file:org.apache.fop.render.ps.PSRenderer.java

/** {@inheritDoc} */
protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
    endTextObject();/* w w w  .j  av a2  s. c  o  m*/
    int x = currentIPPosition + (int) Math.round(pos.getX());
    int y = currentBPPosition + (int) Math.round(pos.getY());
    uri = URISpecification.getURL(uri);
    if (log.isDebugEnabled()) {
        log.debug("Handling image: " + uri);
    }
    int width = (int) pos.getWidth();
    int height = (int) pos.getHeight();
    Rectangle targetRect = new Rectangle(x, y, width, height);

    ImageManager manager = getUserAgent().getFactory().getImageManager();
    ImageInfo info = null;
    try {
        ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
        info = manager.getImageInfo(uri, sessionContext);

        PSRenderingContext renderingContext = new PSRenderingContext(getUserAgent(), gen, getFontInfo());

        if (!isOptimizeResources() || PSImageUtils.isImageInlined(info, renderingContext)) {
            if (log.isDebugEnabled()) {
                log.debug("Image " + info + " is inlined");
            }

            //Determine supported flavors
            ImageFlavor[] flavors;
            ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry();
            flavors = imageHandlerRegistry.getSupportedFlavors(renderingContext);

            //Only now fully load/prepare the image
            Map hints = ImageUtil.getDefaultHints(sessionContext);
            org.apache.xmlgraphics.image.loader.Image img = manager.getImage(info, flavors, hints,
                    sessionContext);

            //Get handler for image
            ImageHandler basicHandler = imageHandlerRegistry.getHandler(renderingContext, img);

            //...and embed as inline image
            basicHandler.handleImage(renderingContext, img, targetRect);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Image " + info + " is embedded as a form later");
            }
            //Don't load image at this time, just put a form placeholder in the stream
            PSResource form = getFormForImage(info.getOriginalURI());
            PSImageUtils.drawForm(form, info, targetRect, gen);
        }

    } catch (ImageException ie) {
        ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                .get(getUserAgent().getEventBroadcaster());
        eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
    } catch (FileNotFoundException fe) {
        ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                .get(getUserAgent().getEventBroadcaster());
        eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
    } catch (IOException ioe) {
        ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                .get(getUserAgent().getEventBroadcaster());
        eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
    }
}

From source file:savant.view.tracks.BAMTrackRenderer.java

/**
 * Render the individual bases on top of the read. Depending on the drawing
 * mode this can be either bases read or mismatches.
 *//*from   w w w  .  j a v  a 2  s  .  co  m*/
private void renderBases(Graphics2D g2, GraphPaneAdapter gp, SAMRecord samRecord, int level, byte[] refSeq,
        Range range, double unitHeight) {

    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);

    boolean baseQualityEnabled = (Boolean) instructions.get(DrawingInstruction.BASE_QUALITY);
    boolean drawingAllBases = lastMode == DrawingMode.SEQUENCE || baseQualityEnabled;

    double unitWidth = gp.getUnitWidth();
    int offset = gp.getOffset();

    // Cutoffs to determine when not to draw
    double leftMostX = gp.transformXPos(range.getFrom());
    double rightMostX = gp.transformXPos(range.getTo()) + unitWidth;

    int alignmentStart = samRecord.getAlignmentStart();

    byte[] readBases = samRecord.getReadBases();
    byte[] baseQualities = samRecord.getBaseQualities();
    boolean sequenceSaved = readBases.length > 0;
    Cigar cigar = samRecord.getCigar();

    // Absolute positions in the reference sequence and the read bases, set after each cigar operator is processed
    int sequenceCursor = alignmentStart;
    int readCursor = alignmentStart;
    List<Rectangle2D> insertions = new ArrayList<Rectangle2D>();

    FontMetrics fm = g2.getFontMetrics(MISMATCH_FONT);
    Rectangle2D charRect = fm.getStringBounds("G", g2);
    boolean fontFits = charRect.getWidth() <= unitWidth && charRect.getHeight() <= unitHeight;
    if (fontFits) {
        g2.setFont(MISMATCH_FONT);
    }
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (CigarElement cigarElement : cigar.getCigarElements()) {

        int operatorLength = cigarElement.getLength();
        CigarOperator operator = cigarElement.getOperator();
        Rectangle2D.Double opRect = null;

        double opStart = gp.transformXPos(sequenceCursor);
        double opWidth = operatorLength * unitWidth;

        // Cut off start and width so no drawing happens off-screen, must be done in the order w, then x, since w depends on first value of x
        double x2 = Math.min(rightMostX, opStart + opWidth);
        opStart = Math.max(leftMostX, opStart);
        opWidth = x2 - opStart;

        switch (operator) {
        case D: // Deletion
            if (opWidth > 0.0) {
                renderDeletion(g2, gp, opStart, level, operatorLength, unitHeight);
            }
            break;

        case I: // Insertion
            insertions.add(new Rectangle2D.Double(gp.transformXPos(sequenceCursor),
                    gp.transformYPos(0) - ((level + 1) * unitHeight) - gp.getOffset(), unitWidth, unitHeight));
            break;

        case M: // Match or mismatch
        case X:
        case EQ:
            // some SAM files do not contain the read bases
            if (sequenceSaved || operator == CigarOperator.X) {
                for (int i = 0; i < operatorLength; i++) {
                    // indices into refSeq and readBases associated with this position in the cigar string
                    int readIndex = readCursor - alignmentStart + i;
                    boolean mismatched = false;
                    if (operator == CigarOperator.X) {
                        mismatched = true;
                    } else {
                        int refIndex = sequenceCursor + i - range.getFrom();
                        if (refIndex >= 0 && refSeq != null && refIndex < refSeq.length) {
                            mismatched = refSeq[refIndex] != readBases[readIndex];
                        }
                    }

                    if (mismatched || drawingAllBases) {
                        Color col;
                        if ((mismatched && lastMode != DrawingMode.STANDARD)
                                || lastMode == DrawingMode.SEQUENCE) {
                            col = cs.getBaseColor((char) readBases[readIndex]);
                        } else {
                            col = cs.getColor(samRecord.getReadNegativeStrandFlag() ? ColourKey.REVERSE_STRAND
                                    : ColourKey.FORWARD_STRAND);
                        }

                        if (baseQualityEnabled && col != null) {
                            col = new Color(col.getRed(), col.getGreen(), col.getBlue(), getConstrainedAlpha(
                                    (int) Math.round((baseQualities[readIndex] * 0.025) * 255)));
                        }

                        double xCoordinate = gp.transformXPos(sequenceCursor + i);
                        double top = gp.transformYPos(0) - ((level + 1) * unitHeight) - offset;
                        if (col != null) {
                            opRect = new Rectangle2D.Double(xCoordinate, top, unitWidth, unitHeight);
                            g2.setColor(col);
                            g2.fill(opRect);
                        }
                        if (lastMode != DrawingMode.SEQUENCE && mismatched && fontFits) {
                            // If it's a real mismatch, we want to draw the base letter (space permitting).
                            g2.setColor(new Color(10, 10, 10));
                            String s = new String(readBases, readIndex, 1);
                            charRect = fm.getStringBounds(s, g2);
                            g2.drawString(s, (float) (xCoordinate + (unitWidth - charRect.getWidth()) * 0.5),
                                    (float) (top + fm.getAscent() + (unitHeight - charRect.getHeight()) * 0.5));
                        }
                    }
                }
            }
            break;

        case N: // Skipped
            opRect = new Rectangle2D.Double(opStart, gp.transformYPos(0) - ((level + 1) * unitHeight) - offset,
                    opWidth, unitHeight);
            g2.setColor(cs.getColor(ColourKey.SKIPPED));
            g2.fill(opRect);
            break;

        default: // P - passing, H - hard clip, or S - soft clip
            break;
        }
        if (operator.consumesReadBases()) {
            readCursor += operatorLength;
        }
        if (operator.consumesReferenceBases()) {
            sequenceCursor += operatorLength;
        }
    }
    for (Rectangle2D ins : insertions) {
        drawInsertion(g2, ins.getX(), ins.getY(), ins.getWidth(), ins.getHeight());
    }
}

From source file:figs.treeVisualization.gui.TimeAxisTree2DPanel.java

/**
 *
 * <P>//w w w.  jav a2s  . c  o m
 * The tree area needs to be set before this is called!
 */
protected void drawDatesToLeafs(Graphics2D g2, double cursor, Rectangle2D plotArea) {

    double ol = fDateAxis.getTickMarkOutsideLength();

    for (Iterator<Element> li = fLeafNodes.iterator(); li.hasNext();) {
        Element clade = li.next();
        Calendar leafDate = fLeafDates.get(clade);

        /**
         * Check to see if this clade even has a date; not all clades have to have them.
         */
        if (leafDate == null) {
            continue;
        }

        double dateY = fDateAxis.dateToJava2D(leafDate.getTime(), plotArea);

        Point2D datePt = new Point2D.Double(cursor - ol, dateY);

        /**
         * If we are drawing a phylogram then,
         * we need to draw this further towards the tree.
         */
        Point2D nodePt = this.fTreePainter.cladeToJava2D(clade, this.fLeftTreeArea);
        Point2D lfPt = new Point2D.Double(plotArea.getX(), nodePt.getY());

        g2.setPaint(this.getCladeBranchColor(clade));
        g2.setStroke(this.getCladeBranchStroke(clade));
        g2.draw(new Line2D.Double(lfPt, datePt));
    }
}

From source file:org.apache.fop.render.intermediate.IFRenderer.java

/** {@inheritDoc} */
protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
    Rectangle posInt = new Rectangle(currentIPPosition + (int) pos.getX(), currentBPPosition + (int) pos.getY(),
            (int) pos.getWidth(), (int) pos.getHeight());
    uri = URISpecification.getURL(uri);/* w w  w  .j a  va 2  s.c o m*/
    try {
        establishForeignAttributes(foreignAttributes);
        painter.drawImage(uri, posInt);
        resetForeignAttributes();
    } catch (IFException ife) {
        handleIFException(ife);
    }
}

From source file:org.apache.fop.render.intermediate.IFRenderer.java

/** {@inheritDoc} */
public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
    endTextObject();// w  w w . ja  v  a2s.  com
    Rectangle posInt = new Rectangle(currentIPPosition + (int) pos.getX(), currentBPPosition + (int) pos.getY(),
            (int) pos.getWidth(), (int) pos.getHeight());
    Document doc = fo.getDocument();
    try {
        establishForeignAttributes(fo.getForeignAttributes());
        painter.drawImage(doc, posInt);
        resetForeignAttributes();
    } catch (IFException ife) {
        handleIFException(ife);
    }
}

From source file:org.apache.pdfbox.contentstream.PDFStreamEngine.java

/**
 * Process the given annotation with the specified appearance stream.
 *
 * @param annotation The annotation containing the appearance stream to process.
 * @param appearance The appearance stream to process.
 *//*from w  ww .j  av  a  2 s  .c o m*/
protected void processAnnotation(PDAnnotation annotation, PDAppearanceStream appearance) throws IOException {
    PDResources parent = pushResources(appearance);
    Stack<PDGraphicsState> savedStack = saveGraphicsStack();

    PDRectangle bbox = appearance.getBBox();
    PDRectangle rect = annotation.getRectangle();
    Matrix matrix = appearance.getMatrix();

    // zero-sized rectangles are not valid
    if (rect.getWidth() > 0 && rect.getHeight() > 0) {
        // transformed appearance box  fixme: may be an arbitrary shape
        Rectangle2D transformedBox = bbox.transform(matrix).getBounds2D();

        // compute a matrix which scales and translates the transformed appearance box to align
        // with the edges of the annotation's rectangle
        Matrix a = Matrix.getTranslateInstance(rect.getLowerLeftX(), rect.getLowerLeftY());
        a.concatenate(Matrix.getScaleInstance((float) (rect.getWidth() / transformedBox.getWidth()),
                (float) (rect.getHeight() / transformedBox.getHeight())));
        a.concatenate(
                Matrix.getTranslateInstance((float) -transformedBox.getX(), (float) -transformedBox.getY()));

        // Matrix shall be concatenated with A to form a matrix AA that maps from the appearance's
        // coordinate system to the annotation's rectangle in default user space
        Matrix aa = Matrix.concatenate(matrix, a);

        // make matrix AA the CTM
        getGraphicsState().setCurrentTransformationMatrix(aa);

        // clip to bounding box
        clipToRect(bbox);

        processStreamOperators(appearance);
    }

    restoreGraphicsStack(savedStack);
    popResources(parent);
}

From source file:org.kepler.monitor.MonitorManager.java

/**
 * Gets the location for a port's monitor attribute.
 *//*from   w  w  w  .  j  a  v a 2 s .  co m*/
private double[] _getPortAttributeLocation(final MonitoredEntity item, final IOPort ioport, double[] loc) {
    boolean ok = false;
    double x, y;
    Location portLocation = (Location) ioport.getAttribute("_location");
    if (portLocation == null) {
        Location entityLocation = (Location) item.entity.getAttribute("_location");
        x = entityLocation.getLocation()[0];
        y = entityLocation.getLocation()[1];
        Figure portFigure = _graphController.getFigure(ioport);
        if (portFigure == null) {

        } else {
            Rectangle2D portBounds = portFigure.getBounds();
            if (portBounds == null) {

            } else {
                if (isDebugging) {
                    log.debug("<" + getFullName() + "> " + ioport.getName() + " no _location.  portBounds="
                            + portBounds);
                }
                x += portBounds.getX();
                y += portBounds.getY();
                ok = true;
            }
        }
    } else {
        x = portLocation.getLocation()[0];
        y = portLocation.getLocation()[1];
        ok = true;
        if (isDebugging) {
            log.debug("<" + getFullName() + "> " + ioport.getName() + " port location: " + portLocation);
        }
    }

    if (ok) {
        x += (ioport.isInput() ? -8 : +12);
        y -= 6;

        if (loc == null) {
            loc = new double[2];
        }
        loc[0] = x;
        loc[1] = y;
        return loc;
    } else {
        return null;
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.visio.informationflow.VisioInformationFlowExport.java

private void setTitlePos(Rectangle2D graphAreaBounds, Shape title, List<Shape> queryInfo) {
    double titleTopY = graphAreaBounds.getY() + graphAreaBounds.getHeight() + DISTANCE_TO_MARGIN_INCHES * 2.8
            + title.getHeight() + getQueryInfoHeight(queryInfo);
    setTitlePosAndSize(title, graphAreaBounds.getX(), titleTopY, null);
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/**
 * {@inheritDoc}//from   w w  w  .  jav a 2s.co  m
 * @todo Copied from AbstractPathOrientedRenderer
 */
protected void handleRegionTraits(RegionViewport region) {
    Rectangle2D viewArea = region.getViewArea();
    float startx = (float) (viewArea.getX() / 1000f);
    float starty = (float) (viewArea.getY() / 1000f);
    float width = (float) (viewArea.getWidth() / 1000f);
    float height = (float) (viewArea.getHeight() / 1000f);

    if (region.getRegionReference().getRegionClass() == FO_REGION_BODY) {
        currentBPPosition = region.getBorderAndPaddingWidthBefore();
        currentIPPosition = region.getBorderAndPaddingWidthStart();
    }
    drawBackAndBorders(region, startx, starty, width, height);
}

From source file:org.caleydo.view.domino.internal.Block.java

/**
 * @param r//from www  .  j a va2s .  c  om
 */
public void selectByBounds(Rectangle2D r, EToolState tool) {
    r = (Rectangle2D) r.clone(); // local copy

    Vec2f l = getLocation(); // to relative coordinates;
    r = new Rectangle2D.Double(r.getX() - l.x(), r.getY() - l.y(), r.getWidth(), r.getHeight());
    if (tool == EToolState.BANDS) {
        if (getOutlineShape().intersects(r)) {
            selectMe();
            repaint();
        }
    } else {
        for (Node node : nodes()) {
            if (node.getRectangleBounds().intersects(r)) {
                node.selectByBounds(r);
            }
        }
    }
}