Example usage for java.awt.geom AffineTransform createTransformedShape

List of usage examples for java.awt.geom AffineTransform createTransformedShape

Introduction

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

Prototype

public Shape createTransformedShape(Shape pSrc) 

Source Link

Document

Returns a new Shape object defined by the geometry of the specified Shape after it has been transformed by this transform.

Usage

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.PlotInstanceLegendCreator.java

private void createCategoricalLegendItems(PlotInstance plotInstance, Set<PlotDimension> dimensionSet,
        LegendItemCollection legendItemCollection, Iterable<Double> values) {
    createDimensionTitleLegendItem(plotInstance, dimensionSet, legendItemCollection);

    PlotConfiguration plotConfig = plotInstance.getCurrentPlotConfigurationClone();

    Shape defaultShape = new Ellipse2D.Float(-5f, -5f, 10f, 10f);
    Color defaultOutlineColor = PlotConfiguration.DEFAULT_OUTLINE_COLOR;
    ColorProvider colorProvider = null;/*from w w w.  j a  v  a 2 s . co m*/
    ShapeProvider shapeProvider = null;
    SizeProvider sizeProvider = null;

    DefaultDimensionConfig dimensionConfig = (DefaultDimensionConfig) plotConfig
            .getDimensionConfig(dimensionSet.iterator().next());
    DimensionConfigData dimensionConfigData = plotInstance.getPlotData()
            .getDimensionConfigData(dimensionConfig);
    for (PlotDimension dimension : dimensionSet) {
        if (dimension == PlotDimension.COLOR) {
            colorProvider = dimensionConfigData.getColorProvider();
        } else if (dimension == PlotDimension.SHAPE) {
            shapeProvider = dimensionConfigData.getShapeProvider();
        } else if (dimension == PlotDimension.SIZE) {
            sizeProvider = dimensionConfigData.getSizeProvider();
        }
    }

    // initialize size scale for legend
    ContinuousSizeProvider legendSizeProvider = null;
    if (sizeProvider != null) {
        double minScalingFactor = sizeProvider.getMinScalingFactor();
        double maxScalingFactor = sizeProvider.getMaxScalingFactor();
        double minLegendScalingFactor = MIN_LEGEND_ITEM_SCALING_FACTOR;
        double maxLegendScalingFactor = MAX_LEGEND_ITEM_SCALING_FACTOR;
        if (minScalingFactor > maxScalingFactor) {
            double tmp = minScalingFactor;
            minScalingFactor = maxScalingFactor;
            maxScalingFactor = tmp;
            minLegendScalingFactor = MAX_LEGEND_ITEM_SCALING_FACTOR;
            maxLegendScalingFactor = MIN_LEGEND_ITEM_SCALING_FACTOR;
        }
        legendSizeProvider = new ContinuousSizeProvider(minScalingFactor, maxScalingFactor,
                minLegendScalingFactor, maxLegendScalingFactor, false);
    }

    for (Double value : values) {
        // configure shape and stroke
        Shape shape = defaultShape;
        BasicStroke outlineStroke;
        Color outlineColor = new Color(0, 0, 0, 0);
        if (shapeProvider != null) {
            shape = shapeProvider.getShapeForCategory(value);
            outlineStroke = DEFAULT_OUTLINE_STROKE;
            outlineColor = defaultOutlineColor;
        } else {
            outlineStroke = new BasicStroke();
            if (colorProvider != null) {
                shape = UNDEFINED_SHAPE;
            } else {
                shape = UNDEFINED_SHAPE_AND_COLOR;
            }
        }

        // configure fill paint
        Paint paint = UNDEFINED_COLOR_PAINT;
        if (colorProvider != null) {
            paint = colorProvider.getColorForValue(value);
        }

        double scalingFactor = 1;
        if (sizeProvider != null) {
            // scale shape according to sizeProvider
            scalingFactor = sizeProvider.getScalingFactorForValue(value);
            // scale shape to fit into legend
            scalingFactor = legendSizeProvider.getScalingFactorForValue(scalingFactor);
            AffineTransform transformation = new AffineTransform();
            transformation.scale(scalingFactor, scalingFactor);
            shape = transformation.createTransformedShape(shape);
        }

        String label = dimensionConfigData.getStringForValue(value);
        if (label == null) {
            label = "";
        }

        CustomLegendItem legendItem = new CustomLegendItem(label, null, null, null, shape, paint, outlineStroke,
                outlineColor);
        legendItemCollection.add(legendItem);
    }
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.PlotInstanceLegendCreator.java

/**
 * Creates a continuous legend item for one item in dimensionSet, i.e. dimensionSet must be a
 * set containing exactly one value.//from w  ww .ja  v  a  2  s  .c  o  m
 * 
 * @param dateFormat
 *            format used to format minValue and maxValue as dates, or null if they should be
 *            displayed numerically instead of as dates
 * @throws ChartPlottimeException
 */
private LegendItem createContinuousLegendItem(PlotInstance plotInstance, Set<PlotDimension> dimensionSet,
        double minValue, double maxValue, DateFormat dateFormat) {
    PlotConfiguration plotConfiguration = plotInstance.getCurrentPlotConfigurationClone();
    PlotDimension dimension = dimensionSet.iterator().next();
    DefaultDimensionConfig dimensionConfig = (DefaultDimensionConfig) plotConfiguration
            .getDimensionConfig(dimension);
    DimensionConfigData dimensionConfigData = plotInstance.getPlotData()
            .getDimensionConfigData(dimensionConfig);
    // String label = dimensionConfig.getLabel();
    // if(label == null) {
    // label = I18N.getGUILabel("plotter.unnamed_value_label");
    // }
    String label = "";

    if (dimension == PlotDimension.COLOR) {
        ColorProvider colorProvider = dimensionConfigData.getColorProvider();
        if (!colorProvider.supportsNumericalValues()) {
            throw new RuntimeException(
                    "Color provider for continuous legend item does not support numerical values.");
        }

        // shape dimensions
        final int width = 50;
        final int height = 10;

        // create item paint

        // first disable logarithmic scale on color provider ( -> linear gradient in legend)
        // ContinuousColorProvider continuousColorProvider = null;
        // if (dimensionConfig.isLogarithmic() && colorProvider instanceof
        // ContinuousColorProvider) {
        // continuousColorProvider = (ContinuousColorProvider)colorProvider;
        // continuousColorProvider.setLogarithmic(false);
        // }

        // calculate gradient
        float fractions[] = new float[width];
        Color colors[] = new Color[width];
        for (int i = 0; i < width; ++i) {

            float fraction = i / (width - 1.0f);
            double fractionValue;
            if (colorProvider instanceof ContinuousColorProvider
                    && ((ContinuousColorProvider) colorProvider).isColorMinMaxValueDifferentFromOriginal(
                            ((ContinuousColorProvider) colorProvider).getMinValue(),
                            ((ContinuousColorProvider) colorProvider).getMaxValue())) {
                fractionValue = ((ContinuousColorProvider) colorProvider).getMinValue()
                        + fraction * (((ContinuousColorProvider) colorProvider).getMaxValue()
                                - ((ContinuousColorProvider) colorProvider).getMinValue());
            } else {
                fractionValue = minValue + fraction * (maxValue - minValue);
            }
            colors[i] = colorProvider.getColorForValue(fractionValue);
            fractions[i] = fraction;
        }
        LinearGradientPaint shapeFillPaint = new LinearGradientPaint(new Point(0, 0), new Point(width, 0),
                fractions, colors, CycleMethod.REPEAT);

        // reset color provider to logarithmic if necessary
        // if (continuousColorProvider != null && dimensionConfig.isLogarithmic()) {
        // continuousColorProvider.setLogarithmic(true);
        // }

        // create item shape
        Rectangle itemShape = new Rectangle(width, height);

        if (colorProvider instanceof ContinuousColorProvider) {
            return createFlankedShapeLegendItem(label, ((ContinuousColorProvider) colorProvider).getMinValue(),
                    ((ContinuousColorProvider) colorProvider).getMaxValue(), itemShape, shapeFillPaint, true,
                    dateFormat);
        } else {
            return createFlankedShapeLegendItem(label, minValue, maxValue, itemShape, shapeFillPaint, true,
                    dateFormat);
        }
    } else if (dimension == PlotDimension.SHAPE) {
        // shape provider probably never supports numerical values
        return null;
    } else if (dimension == PlotDimension.SIZE) {
        SizeProvider sizeProvider = dimensionConfigData.getSizeProvider();

        if (!sizeProvider.supportsNumericalValues()) {
            throw new RuntimeException(
                    "Size provider for continuous legend item does not support numerical values.");
        }

        double minScalingFactor = sizeProvider.getMinScalingFactor();
        double maxScalingFactor = sizeProvider.getMaxScalingFactor();
        ContinuousSizeProvider legendSizeProvider = new ContinuousSizeProvider(minScalingFactor,
                maxScalingFactor, MIN_LEGEND_ITEM_SCALING_FACTOR, MAX_LEGEND_ITEM_SCALING_FACTOR, false);

        int legendItemCount = 4;
        Area composedShape = new Area();
        Shape originalShape = UNDEFINED_SHAPE;
        if (dimensionSet.contains(PlotDimension.SIZE) && dimensionSet.size() == 1) {
            originalShape = UNDEFINED_SHAPE_AND_COLOR;
        }
        double maxHeight = originalShape.getBounds().getHeight() * MAX_LEGEND_ITEM_SCALING_FACTOR;
        for (int i = 0; i < legendItemCount; ++i) {
            double fraction = minScalingFactor
                    + ((double) i / legendItemCount * (maxScalingFactor - minScalingFactor));
            double legendScalingFactor = legendSizeProvider.getScalingFactorForValue(fraction);

            double composedWidth = composedShape.getBounds().getWidth();

            AffineTransform t = new AffineTransform();
            t.scale(legendScalingFactor, legendScalingFactor);
            Shape shape = t.createTransformedShape(originalShape);

            t = new AffineTransform();
            double shapeWidth = shape.getBounds().getWidth();
            double shapeHeight = shape.getBounds().getHeight();
            t.translate(composedWidth + shapeWidth * .1, (maxHeight - shapeHeight) / 2.0);
            t.translate(-shape.getBounds().getMinX(), -shape.getBounds().getMinY());
            shape = t.createTransformedShape(shape);
            composedShape.add(new Area(shape));
        }

        return createFlankedShapeLegendItem(label, minValue, maxValue, composedShape, UNDEFINED_COLOR_PAINT,
                false, dateFormat);

    } else {
        throw new RuntimeException("Unsupported dimension. Execution path should never reach this line.");
    }
}

From source file:ExtendedGeneralPath.java

/**
 * Adds an elliptical arc, defined by two radii, an angle from the
 * x-axis, a flag to choose the large arc or not, a flag to
 * indicate if we increase or decrease the angles and the final
 * point of the arc.//from  w  w  w  . j  av a2s  . c o m
 *
 * @param rx the x radius of the ellipse
 * @param ry the y radius of the ellipse
 *
 * @param angle the angle from the x-axis of the current
 * coordinate system to the x-axis of the ellipse in degrees.
 *
 * @param largeArcFlag the large arc flag. If true the arc
 * spanning less than or equal to 180 degrees is chosen, otherwise
 * the arc spanning greater than 180 degrees is chosen
 *
 * @param sweepFlag the sweep flag. If true the line joining
 * center to arc sweeps through decreasing angles otherwise it
 * sweeps through increasing angles
 *
 * @param x the absolute x coordinate of the final point of the arc.
 * @param y the absolute y coordinate of the final point of the arc.
 */
public synchronized void arcTo(float rx, float ry, float angle, boolean largeArcFlag, boolean sweepFlag,
        float x, float y) {

    // Ensure radii are valid
    if (rx == 0 || ry == 0) {
        lineTo(x, y);
        return;
    }

    checkMoveTo(); // check if prev command was moveto

    // Get the current (x, y) coordinates of the path
    double x0 = cx;
    double y0 = cy;
    if (x0 == x && y0 == y) {
        // If the endpoints (x, y) and (x0, y0) are identical, then this
        // is equivalent to omitting the elliptical arc segment entirely.
        return;
    }

    Arc2D arc = computeArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y);
    if (arc == null)
        return;

    AffineTransform t = AffineTransform.getRotateInstance(Math.toRadians(angle), arc.getCenterX(),
            arc.getCenterY());
    Shape s = t.createTransformedShape(arc);
    path.append(s, true);

    makeRoom(7);
    types[numSeg++] = ExtendedPathIterator.SEG_ARCTO;
    values[numVals++] = rx;
    values[numVals++] = ry;
    values[numVals++] = angle;
    values[numVals++] = largeArcFlag ? 1 : 0;
    values[numVals++] = sweepFlag ? 1 : 0;
    cx = values[numVals++] = x;
    cy = values[numVals++] = y;
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.PlotInstanceLegendCreator.java

private CustomLegendItem createValueSourceLegendItem(PlotConfiguration plotConfig, ValueSource valueSource) {

    Set<PlotDimension> dimensions = new HashSet<PlotDimension>();
    for (PlotDimension dimension : PlotDimension.values()) {
        switch (dimension) {
        case DOMAIN:
        case VALUE:
            break;
        default://  ww  w .  j  a  v  a 2 s  . c  o  m
            if (valueSource.useSeriesFormatForDimension(plotConfig, dimension)) {
                dimensions.add(dimension);
            }
        }
    }
    if (dimensions.isEmpty()) {
        return null;
    }

    SeriesFormat format = valueSource.getSeriesFormat();
    String description = "";
    String toolTipText = "";
    String urlText = "";
    boolean shapeVisible = true;
    Shape shape;
    boolean shapeFilled = true;
    Paint fillPaint = UNDEFINED_COLOR_PAINT;
    boolean shapeOutlineVisible = true;
    Paint outlinePaint = PlotConfiguration.DEFAULT_OUTLINE_COLOR;
    Stroke outlineStroke = DEFAULT_OUTLINE_STROKE;
    boolean lineVisible = format.getLineStyle() != LineStyle.NONE
            && format.getSeriesType() == SeriesFormat.VisualizationType.LINES_AND_SHAPES;

    // configure fill paint and line paint
    Paint linePaint;
    String label = valueSource.toString();
    if (label == null) {
        label = "";
    }
    if (dimensions.contains(PlotDimension.COLOR)) {
        Color color = format.getItemColor();
        fillPaint = format.getAreaFillPaint(color);
        linePaint = fillPaint;
    } else {
        if (format.getAreaFillStyle() == FillStyle.NONE) {
            fillPaint = new Color(0, 0, 0, 0);
            linePaint = fillPaint;
        } else if (format.getAreaFillStyle() == FillStyle.SOLID) {
            fillPaint = UNDEFINED_COLOR_PAINT;
            linePaint = UNDEFINED_LINE_COLOR;
        } else {
            fillPaint = format.getAreaFillPaint(UNDEFINED_COLOR);
            linePaint = fillPaint;
        }

    }

    VisualizationType seriesType = valueSource.getSeriesFormat().getSeriesType();
    if (seriesType == VisualizationType.LINES_AND_SHAPES) {
        if (dimensions.contains(PlotDimension.SHAPE)) {
            shape = format.getItemShape().getShape();
        } else if (dimensions.contains(PlotDimension.COLOR)) {
            shape = UNDEFINED_SHAPE;
        } else {
            shape = UNDEFINED_SHAPE_AND_COLOR;
        }

        if (dimensions.contains(PlotDimension.SIZE)) {
            AffineTransform transformation = new AffineTransform();
            double scalingFactor = format.getItemSize();
            transformation.scale(scalingFactor, scalingFactor);
            shape = transformation.createTransformedShape(shape);
        }
    } else if (seriesType == VisualizationType.BARS) {
        shape = BAR_SHAPE;
    } else if (seriesType == VisualizationType.AREA) {
        shape = AREA_SHAPE;
    } else {
        throw new RuntimeException("Unknown SeriesType. This should not happen.");
    }

    // configure line shape
    float lineLength = 0;
    if (lineVisible) {
        lineLength = format.getLineWidth();
        if (lineLength < 1) {
            lineLength = 1;
        }
        if (lineLength > 1) {
            lineLength = 1 + (float) Math.log(lineLength) / 2;
        }

        // line at least 30 pixels long, and show at least 2 iterations of stroke
        lineLength = Math.max(lineLength * 30, format.getStrokeLength() * 2);

        // line at least 2x longer than shape width
        if (shape != null) {
            lineLength = Math.max(lineLength, (float) shape.getBounds().getWidth() * 2f);
        }
    }

    // now create line shape and stroke
    Shape line = new Line2D.Float(0, 0, lineLength, 0);
    BasicStroke lineStroke = format.getStroke();
    if (lineStroke == null) {
        lineStroke = new BasicStroke();
    }

    // unset line ending decoration to prevent drawing errors in legend
    {
        BasicStroke s = lineStroke;
        lineStroke = new BasicStroke(s.getLineWidth(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND,
                s.getMiterLimit(), s.getDashArray(), s.getDashPhase());
    }

    return new CustomLegendItem(label, description, toolTipText, urlText, shapeVisible, shape, shapeFilled,
            fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible, line, lineStroke,
            linePaint);
}

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

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

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

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

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

/**
 * Paints the vertex <code>v</code> at the location <code>(x,y)</code>
 * on the graphics context <code>g_gen</code>.  The vertex is painted
 * using the shape returned by this instance's <code>VertexShapeFunction</code>,
 * and the foreground and background (border) colors provided by this
 * instance's <code>VertexColorFunction</code>.  Delegates drawing the
 * label (if any) for this vertex to <code>labelVertex</code>.
 *//*from   w  ww . j  ava2s  .  c o m*/
public void paintVertex(Graphics g, Vertex v, int x, int y) {
    if (!vertexIncludePredicate.evaluate(v))
        return;

    boolean vertexHit = true;
    Rectangle deviceRectangle = null;
    Graphics2D g2d = (Graphics2D) g;
    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);
    }

    Stroke old_stroke = g2d.getStroke();
    Stroke new_stroke = vertexStrokeFunction.getStroke(v);
    if (new_stroke != null) {
        g2d.setStroke(new_stroke);
    }
    // get the shape to be rendered
    Shape s = vertexShapeFunction.getShape(v);

    // create a transform that translates to the location of
    // the vertex to be rendered
    AffineTransform xform = AffineTransform.getTranslateInstance(x, y);
    // transform the vertex shape with xtransform
    s = xform.createTransformedShape(s);

    vertexHit = viewTransformer.transform(s).intersects(deviceRectangle);

    if (vertexHit) {

        if (vertexIconFunction != null) {
            paintIconForVertex(g2d, v, x, y);
        } else {
            paintShapeForVertex(g2d, v, s);
        }

        if (new_stroke != null) {
            g2d.setStroke(old_stroke);
        }
        String label = vertexStringer.getLabel(v);
        if (label != null) {
            labelVertex(g, v, label, x, y);
        }
    }
}

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

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

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

/**
 * Retrieves the shape template for <code>e</code> and
 * transforms it according to the positions of its endpoints
 * in <code>layout</code>.//  ww w.j a  va  2 s. c  o  m
 * @param layout the <code>Layout</code> which specifies
 * <code>e</code>'s endpoints' positions
 * @param e the edge whose shape is to be returned
 * @return
 */
private Shape getTransformedEdgeShape(Layout<V, E> layout, E e) {
    Pair<V> pair = layout.getGraph().getEndpoints(e);
    V v1 = pair.getFirst();
    V v2 = pair.getSecond();
    boolean isLoop = v1.equals(v2);
    Point2D p1 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v1));
    Point2D p2 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v2));
    if (p1 == null || p2 == null)
        return null;
    float x1 = (float) p1.getX();
    float y1 = (float) p1.getY();
    float x2 = (float) p2.getX();
    float y2 = (float) p2.getY();

    // translate the edge to the starting vertex
    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);

    Shape edgeShape = vv.getRenderContext().getEdgeShapeTransformer()
            .transform(Context.<Graph<V, E>, E>getInstance(vv.getGraphLayout().getGraph(), e));
    if (isLoop) {
        // make the loops proportional to the size of the vertex
        Shape s2 = vv.getRenderContext().getVertexShapeTransformer().transform(v2);
        Rectangle2D s2Bounds = s2.getBounds2D();
        xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight());
        // move the loop so that the nadir is centered in the vertex
        xform.translate(0, -edgeShape.getBounds2D().getHeight() / 2);
    } else {
        float dx = x2 - x1;
        float dy = y2 - y1;
        // rotate the edge to the angle between the vertices
        double theta = Math.atan2(dy, dx);
        xform.rotate(theta);
        // stretch the edge to span the distance between the vertices
        float dist = (float) Math.sqrt(dx * dx + dy * dy);
        xform.scale(dist, 1.0f);
    }

    // transform the edge to its location and dimensions
    edgeShape = xform.createTransformedShape(edgeShape);
    return edgeShape;
}

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>.
 *//*from w  w w  .  j  av a2 s  .c om*/
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:org.apache.fop.render.intermediate.IFRenderer.java

/** {@inheritDoc} */
public void renderInlineParent(InlineParent ip) {
    // stuff we only need if a link must be created:
    Rectangle ipRect = null;/*from  w  ww . j av a  2 s . c o m*/
    AbstractAction action = null;
    // make sure the rect is determined *before* calling super!
    int ipp = currentIPPosition;
    int bpp = currentBPPosition + ip.getBlockProgressionOffset();
    ipRect = new Rectangle(ipp, bpp, ip.getIPD(), ip.getBPD());
    AffineTransform transform = graphicContext.getTransform();
    ipRect = transform.createTransformedShape(ipRect).getBounds();

    // render contents
    super.renderInlineParent(ip);

    boolean linkTraitFound = false;

    // try INTERNAL_LINK first
    Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK);
    if (intLink != null) {
        linkTraitFound = true;
        String pvKey = intLink.getPVKey();
        String idRef = intLink.getIDRef();
        boolean pvKeyOK = pvKey != null && pvKey.length() > 0;
        boolean idRefOK = idRef != null && idRef.length() > 0;
        if (pvKeyOK && idRefOK) {
            Integer pageIndex = (Integer) pageIndices.get(pvKey);
            action = getGoToActionForID(idRef, (pageIndex != null ? pageIndex.intValue() : -1));
        } else {
            //Warnings already issued by AreaTreeHandler
        }
    }

    // no INTERNAL_LINK, look for EXTERNAL_LINK
    if (!linkTraitFound) {
        Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK);
        if (extLink != null) {
            String extDest = extLink.getDestination();
            if (extDest != null && extDest.length() > 0) {
                linkTraitFound = true;
                action = new URIAction(extDest, extLink.newWindow());
                action = actionSet.put(action);
            }
        }
    }

    // warn if link trait found but not allowed, else create link
    if (linkTraitFound) {
        StructureTreeElement structElem = (StructureTreeElement) ip.getTrait(Trait.STRUCTURE_TREE_ELEMENT);
        action.setStructureTreeElement(structElem);
        Link link = new Link(action, ipRect);
        this.deferredLinks.add(link);
    }
}