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: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 ww  . j a  v a  2 s.  c o 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:com.newatlanta.bluedragon.CategoryAxis.java

public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge,
        AxisSpace space) {//from  w  w w. j a v  a2 s. c om

    // create a new space object if one wasn't supplied...
    if (space == null) {
        space = new AxisSpace();
    }

    // if the axis is not visible, no additional space is required...
    if (!isVisible()) {
        return space;
    }

    // calculate the max size of the tick labels (if visible)...
    double tickLabelHeight = 0.0;
    double tickLabelWidth = 0.0;
    if (isTickLabelsVisible()) {
        g2.setFont(getTickLabelFont());
        AxisState state = new AxisState();
        // we call refresh ticks just to get the maximum width or height
        if (RectangleEdge.isTopOrBottom(edge)) {
            // BEGIN fix for category labels that wrap
            // If space has been reserved to the left and right then we need to
            // reduce the plot area
            // by this amount so that the space needed by category labels that wrap
            // on to multiple lines
            // will be calculated properly.
            Rectangle2D newPlotArea = new Rectangle2D.Double(plotArea.getX(), plotArea.getY(),
                    plotArea.getWidth() - space.getLeft() - space.getRight(), plotArea.getHeight());
            refreshTicks(g2, state, newPlotArea, edge);
            // END fix for category labels that wrap
        } else {
            refreshTicks(g2, state, plotArea, edge);
        }
        if (edge == RectangleEdge.TOP) {
            tickLabelHeight = state.getMax();
        } else if (edge == RectangleEdge.BOTTOM) {
            tickLabelHeight = state.getMax();
        } else if (edge == RectangleEdge.LEFT) {
            tickLabelWidth = state.getMax();
        } else if (edge == RectangleEdge.RIGHT) {
            tickLabelWidth = state.getMax();
        }
    }

    // get the axis label size and update the space object...
    Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
    double labelHeight = 0.0;
    double labelWidth = 0.0;
    if (RectangleEdge.isTopOrBottom(edge)) {
        labelHeight = labelEnclosure.getHeight();
        space.add(labelHeight + tickLabelHeight + this.getCategoryLabelPositionOffset(), edge);
    } else if (RectangleEdge.isLeftOrRight(edge)) {
        labelWidth = labelEnclosure.getWidth();
        space.add(labelWidth + tickLabelWidth + this.getCategoryLabelPositionOffset(), edge);
    }
    return space;

}

From source file:de.codesourcery.planning.swing.PlanningCanvas.java

private BoundingBox renderSlotTitle(IFactorySlot slot, RenderContext ctx, boolean layoutOnly) {
    final String label = labelProvider.getLabel(slot);
    if (StringUtils.isBlank(label)) {
        return null;
    }//from  w  ww .  j ava  2s. c  o  m

    final Rectangle2D labelBounds = ctx.getLabelBounds(label);

    final int y = ctx.currentY;

    int width;
    if (!layoutOnly) {
        width = ctx.xTimelineStart;
        ctx.drawLabel(ctx.viewport.getX(), y, label);
    } else {
        width = (int) (labelBounds.getWidth() + ctx.options.getSlotTitleRightBorder());
    }

    final BoundingBox boundingBox = createBoundingBox(ctx.viewport.getX(), y, width,
            (int) labelBounds.getHeight());

    // make sure all slot titles are rendered 
    // at the same width ( = width of longest slot title)
    if (layoutOnly && width > ctx.xTimelineStart) {
        ctx.xTimelineStart = ctx.viewport.getX() + width;
    }

    return boundingBox;
}

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

private void renderSNPMode(Graphics2D g2, GraphPaneAdapter gp, Resolution r) throws RenderingException {

    Genome genome = GenomeController.getInstance().getGenome();
    if (!genome.isSequenceSet()) {
        throw new RenderingException("No reference sequence loaded\nSwitch to standard display mode",
                RenderingException.WARNING_PRIORITY);
    }//from   w  w  w  .java 2 s  .  com

    AxisRange axisRange = (AxisRange) instructions.get(DrawingInstruction.AXIS_RANGE);
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);

    List<Pileup> pileups = new ArrayList<Pileup>();

    // make the pileups
    int length = axisRange.getXMax() - axisRange.getXMin() + 1;
    assert Math.abs(axisRange.getXMin()) <= Integer.MAX_VALUE;
    int startPosition = (int) axisRange.getXMin();
    for (int j = 0; j < length; j++) {
        pileups.add(new Pileup(startPosition + j));
    }

    // Go through the samrecords and edit the pileups
    for (Record record : data) {
        SAMRecord samRecord = ((BAMIntervalRecord) record).getSAMRecord();
        updatePileupsFromSAMRecord(pileups, samRecord, startPosition);
    }

    double maxHeight = 0;
    for (Pileup p : pileups) {
        int current = p.getTotalCoverage(null);
        if (current > maxHeight) {
            maxHeight = current;
        }
    }

    gp.setXRange(axisRange.getXRange());
    gp.setYRange(new Range(0, (int) Math.rint((double) maxHeight / 0.9)));

    double unitHeight = (Math.rint(gp.transformYPos(0) * 0.9)) / maxHeight;
    double unitWidth = gp.getUnitWidth();

    ColourAccumulator accumulator = new ColourAccumulator(cs);
    List<Rectangle2D> insertions = new ArrayList<Rectangle2D>();

    for (Pileup p : pileups) {
        int totalCoverage = p.getTotalCoverage(null);
        if (totalCoverage > 0) {
            double bottom = gp.transformYPos(0);
            double x = gp.transformXPos(p.getPosition());

            VariantType genomeNuc = VariantType.fromChar((char) refSeq[p.getPosition() - startPosition]);
            VariantType snpNuc = genomeNuc;

            // Only record a shape if we have at least some mismatches.
            if (totalCoverage > p.getCoverage(genomeNuc, null)) {
                // Reduce height for insertions, since they don't contribute to the height.
                double h = unitHeight * (totalCoverage - p.getCoverage(VariantType.INSERTION, null));
                recordToShapeMap.put(new PileupRecord(p, false),
                        new Rectangle2D.Double(x, bottom - h, unitWidth, h));
            }

            while ((genome.isSequenceSet() && (snpNuc = p.getLargestVariantType(genomeNuc)) != null)
                    || ((snpNuc = p.getLargestVariantType(VariantType.OTHER)) != null)) {
                double h = unitHeight * p.getCoverage(snpNuc, null);
                Rectangle2D rect = new Rectangle2D.Double(x, bottom - h, unitWidth, h);
                accumulator.addShape(getSubPileColour(snpNuc, genomeNuc), rect);
                if (snpNuc == VariantType.INSERTION) {
                    insertions.add(rect);
                } else {
                    bottom -= h;
                }
                p.clearVariantType(snpNuc);
            }
        }
    }

    accumulator.fill(g2);
    for (Rectangle2D ins : insertions) {
        drawInsertion(g2, ins.getX(), ins.getY(), ins.getWidth(), ins.getHeight());
    }
}

From source file:org.dwfa.ace.graph.AceGraphRenderer.java

/**
 * Labels the specified vertex with the specified label.
 * Uses the font specified by this instance's
 * <code>VertexFontFunction</code>. (If the font is unspecified, the
 * existing//  w ww. java2s. c om
 * font for the graphics context is used.) If vertex label centering
 * is active, the label is centered on the position of the vertex; otherwise
 * the label is offset slightly.
 */
protected void labelVertex(Graphics g, Vertex v, String label, int x, int y) {
    Component component = prepareRenderer(graphLabelRenderer, label, isPicked(v), v);

    Dimension d = component.getPreferredSize();

    int h_offset;
    int v_offset;
    if (centerVertexLabel) {
        h_offset = -d.width / 2;
        v_offset = -d.height / 2;

    } else {
        Rectangle2D bounds = vertexShapeFunction.getShape(v).getBounds2D();
        h_offset = (int) (bounds.getWidth() / 2) + 5;
        v_offset = (int) (bounds.getHeight() / 2) + 5 - d.height;
    }

    component.setBackground(Color.white);
    rendererPane.paintComponent(g, component, screenDevice, x + h_offset, y + v_offset, d.width, d.height,
            true);

}

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

private void createNamesLegend(Rectangle2D legendsBox) throws MasterNotFoundException {
    double frameX = legendsBox.getX();
    double frameY = legendsBox.getY() - getTargetPage().getHeight() + MARGIN_IN;
    double frameWidth = legendsBox.getWidth();
    double frameHeight = getTargetPage().getHeight() - legendsBox.getHeight() - DISTANCE_TO_MARGIN_INCHES;
    createNamesLegend(frameX, frameY, frameWidth, frameHeight, informationFlowOptions.isNakedExport(),
            MessageAccess.getStringOrNull("graphicalExport.informationflow.title", getLocale()));
}

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

private void renderStrandSNPMode(Graphics2D g2, GraphPaneAdapter gp, Resolution r) throws RenderingException {

    Genome genome = GenomeController.getInstance().getGenome();
    if (!genome.isSequenceSet()) {
        throw new RenderingException("No reference sequence loaded\nSwitch to standard display mode",
                RenderingException.WARNING_PRIORITY);
    }/*from   w w w  .  j av a 2 s . c o m*/

    AxisRange axisRange = (AxisRange) instructions.get(DrawingInstruction.AXIS_RANGE);
    int xMin = axisRange.getXMin();
    int xMax = axisRange.getXMax();
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);

    List<Pileup> pileups = new ArrayList<Pileup>();

    // make the pileups
    for (int j = xMin; j <= xMax; j++) {
        pileups.add(new Pileup(j));
    }

    // Go through the samrecords and edit the pileups
    for (Record record : data) {
        SAMRecord samRecord = ((BAMIntervalRecord) record).getSAMRecord();
        updatePileupsFromSAMRecord(pileups, samRecord, xMin);
    }

    double maxHeight = 0.0;
    for (Pileup p : pileups) {
        int current1 = p.getTotalCoverage(Strand.REVERSE);
        int current2 = p.getTotalCoverage(Strand.FORWARD);
        if (current1 > maxHeight) {
            maxHeight = current1;
        }
        if (current2 > maxHeight) {
            maxHeight = current2;
        }
    }
    int yMax = (int) Math.ceil(maxHeight / 0.9);
    gp.setYRange(new Range(-yMax, yMax));
    instructions.put(DrawingInstruction.AXIS_RANGE, new AxisRange(xMin, xMax, -yMax, yMax));

    ColourAccumulator accumulator = new ColourAccumulator(cs);
    List<Rectangle2D> insertions = new ArrayList<Rectangle2D>();

    double unitHeight = gp.getUnitHeight();
    double unitWidth = gp.getUnitWidth();
    double axis = gp.transformYPos(0.0);

    for (Pileup p : pileups) {

        if (p.getTotalCoverage(null) > 0) {
            VariantType snpNuc = null;
            double bottom = axis;
            double top = axis;
            double x = gp.transformXPos(p.getPosition());

            VariantType genomeNuc = null;
            if (genome.isSequenceSet()) {
                genomeNuc = VariantType.fromChar((char) refSeq[p.getPosition() - xMin]);
                snpNuc = genomeNuc;
            }

            // Only record a shape if we have at least some mismatches.
            int totalCoverage = p.getTotalCoverage(null);
            if (totalCoverage > p.getCoverage(genomeNuc, null)) {
                double h = unitHeight * (totalCoverage - p.getCoverage(VariantType.INSERTION, null));
                recordToShapeMap
                        .put(new PileupRecord(p, true),
                                new Rectangle2D.Double(x,
                                        bottom - unitHeight * (p.getTotalCoverage(Strand.FORWARD)
                                                - p.getCoverage(VariantType.INSERTION, Strand.FORWARD)),
                                        unitWidth, h));
            }

            while ((genome.isSequenceSet() && (snpNuc = p.getLargestVariantType(genomeNuc)) != null)
                    || ((snpNuc = p.getLargestVariantType(null)) != null)) {

                int forwardCoverage = p.getCoverage(snpNuc, Strand.FORWARD);
                int reverseCoverage = p.getCoverage(snpNuc, Strand.REVERSE);

                ColourKey col = getSubPileColour(snpNuc, genomeNuc);
                if (forwardCoverage > 0) {
                    double h = unitHeight * forwardCoverage;
                    Rectangle2D rect = new Rectangle2D.Double(x, bottom - h, unitWidth, h);
                    accumulator.addShape(col == ColourKey.REVERSE_STRAND ? ColourKey.FORWARD_STRAND : col,
                            rect);
                    if (snpNuc == VariantType.INSERTION) {
                        insertions.add(rect);
                    } else {
                        bottom -= h;
                    }
                }
                if (reverseCoverage > 0) {
                    double h = unitHeight * reverseCoverage;
                    Rectangle2D rect = new Rectangle2D.Double(x, top, unitWidth, h);
                    accumulator.addShape(col, rect);
                    if (snpNuc == VariantType.INSERTION) {
                        insertions.add(rect);
                    } else {
                        top += h;
                    }
                }

                p.clearVariantType(snpNuc);
            }
        }
    }

    accumulator.fill(g2);
    for (Rectangle2D ins : insertions) {
        drawInsertion(g2, ins.getX(), ins.getY(), ins.getWidth(), ins.getHeight());
    }

    g2.setColor(Color.BLACK);
    g2.draw(new Line2D.Double(0, axis, gp.getWidth(), axis));
}

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

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    g2.setPaint(plot.paint);/* www. ja va 2 s .com*/

    if (pass == 1) {
        if (image != null) {
            double x = dataArea.getX();
            double y = dataArea.getY();
            //there is a problem when using Graphics2D with affine transform 
            //and BufferedImage; using subclass of Image returned below.
            //rescaling needed because adding legend causes dataArea to change.
            Image scaledImage = image.getScaledInstance((int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, Image.SCALE_DEFAULT);
            g2.drawImage(scaledImage, (int) x + 1, (int) y + 1, (int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, this);
            //g2.translate(-1,-1);
            //g2.drawRect((int) x, (int) y, (int) dataArea.getWidth(),(int) dataArea.getHeight());
            //g2.translate(1,1);
        }
        return true;
    }

    final double parHStep, parVStep;
    double parHLower = plot.getDomainAxis().getRange().getLowerBound();
    double parHUpper = plot.getDomainAxis().getRange().getUpperBound();
    double parVLower = plot.getRangeAxis().getRange().getLowerBound();
    double parVUpper = plot.getRangeAxis().getRange().getUpperBound();

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

    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;

    if (model instanceof ODE) {
        double step = stepSize; // stepSize and timeStep probably mean the same thing, one for discrete another for ODE
        double[] result = new double[model.getNVar()];

        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);

                int color;
                result = Lua.evaluateLyapunovExponentsODE(model, parameters, initialPoint, timePeriod,
                        stepSize);

                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);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                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);
                }
            } //end for
        } //end for
    } //end if ODE
    else {
        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;

                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);

                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);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                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);
            } //end for
        } //end for
    } //end else
    return true;
}

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   ww  w  .j a va 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:org.apache.fop.render.ps.PSRenderer.java

/**
 * {@inheritDoc}/*w  w w. j  av  a  2  s. co m*/
 */
protected void startVParea(CTM ctm, Rectangle2D clippingRect) {
    saveGraphicsState();
    if (clippingRect != null) {
        clipRect((float) clippingRect.getX() / 1000f, (float) clippingRect.getY() / 1000f,
                (float) clippingRect.getWidth() / 1000f, (float) clippingRect.getHeight() / 1000f);
    }
    // multiply with current CTM
    final double[] matrix = ctm.toArray();
    matrix[4] /= 1000f;
    matrix[5] /= 1000f;
    concatMatrix(matrix);
}