Example usage for java.awt Graphics2D getTransform

List of usage examples for java.awt Graphics2D getTransform

Introduction

In this page you can find the example usage for java.awt Graphics2D getTransform.

Prototype

public abstract AffineTransform getTransform();

Source Link

Document

Returns a copy of the current Transform in the Graphics2D context.

Usage

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void drawString(final String message) {
    Drawable command = new Drawable() {

        @Override/*from  www.  j av  a2 s .  c om*/
        public void draw(Graphics2D g2, TurtleState turtleState) {
            if (!turtleState.penup) {
                AffineTransform saveXform = g2.getTransform();
                //double offsetAngle = (Math.PI / 2.0);
                double offsetAngle = 0;
                g2.setTransform(AffineTransform.getRotateInstance(turtleState.angle + offsetAngle,
                        turtleState.penX, turtleState.penY));
                g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
                g2.drawString(message, (int) turtleState.penX, (int) turtleState.penY);
                g2.setTransform(saveXform);
            }
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

From source file:org.uva.itast.blended.omr.OMRUtils.java

public static void logFrame(PageImage pageImage, PagePoint topleft, PagePoint topright, PagePoint bottomleft,
        PagePoint bottomright, Color color, String label) {
    if (topleft == null || topright == null || bottomleft == null || bottomright == null)
        return;/*  ww  w  . ja va  2s. co m*/

    Graphics2D g = pageImage.getReportingGraphics();
    AffineTransform t = g.getTransform();
    g.setColor(color);
    g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
            new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0));

    // Point framePxUL=pageImage.toPixels(topleft.getX(), topleft.getY());
    // Point framePxUR=pageImage.toPixels(topright.getX(), topright.getY());
    // Point framePxBL=pageImage.toPixels(bottomleft.getX(),
    // bottomleft.getY());
    // Point framePxBR=pageImage.toPixels(bottomright.getX(),
    // bottomright.getY());

    g.drawLine(topleft.getXpx(), topleft.getYpx(), topright.getXpx(), topright.getYpx());
    g.drawLine(topleft.getXpx(), topleft.getYpx(), bottomleft.getXpx(), bottomleft.getYpx());
    g.drawLine(topright.getXpx(), topright.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    g.drawLine(bottomleft.getXpx(), bottomleft.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    if (label != null) {
        g.drawString(label, topleft.getXpx(), topleft.getYpx());
    }
}

From source file:org.uva.itast.blended.omr.pages.PageImage.java

/**
 * Scaled graphics for drawing on a small version of the page.
 * Transform is set for drawing in pixels refered to the original scanned image
 * @return/*  w w w  . j a va2 s . co  m*/
 */
public Graphics2D getReportingGraphics() {
    // TODO: Crear una transformacion equivalente a la de la pgina para la imagen reducida
    BufferedImage reportingImage = this.getReportingImage();
    Graphics2D g = reportingImage.createGraphics();

    //      AffineTransform origTransf=getAllignmentInfo();
    //
    //      AffineTransform trans=(AffineTransform) origTransf.clone();
    //      trans.scale(reportingImage.getWidth()/(getImage().getWidth()),
    //         reportingImage.getHeight()/(getImage().getHeight()));
    //      AffineTransform trans=g.getTransform();
    //      trans.scale(reportingImage.getWidth()/(getPreferredHorizontalResolution()*PageImage.a4width),
    //            reportingImage.getHeight()/(getPreferredVerticalResolution()*PageImage.a4height));
    double scaleX = ((double) reportingImage.getWidth()) / (getImage().getWidth());
    double scaleY = ((double) reportingImage.getHeight()) / (getImage().getHeight());
    AffineTransform trans = g.getTransform();
    trans.scale(scaleX, scaleY);
    g.setTransform(trans);
    return g;
}

From source file:org.uva.itast.blended.omr.scanners.BarcodeScanner.java

/**
 * @param campo/*from  w w  w.j a v a 2s. co m*/
 */
public void markBarcode(Field campo) {
    try {
        //get bbox in pixels
        Rectangle rect = pageImage.toPixels(campo.getBBox());
        // expand the area for some tolerance
        Rectangle2D expandedArea = getExpandedArea(campo.getBBox(), (float) BARCODE_AREA_PERCENT);
        Rectangle expandedRect = pageImage.toPixels(expandedArea);

        Graphics2D g = pageImage.getReportingGraphics();
        AffineTransform t = g.getTransform();
        g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
                new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0));
        if (lastResult != null)
            g.setColor(Color.BLUE);
        else
            g.setColor(Color.RED);

        g.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 3, 3);
        g.drawRoundRect(expandedRect.x, expandedRect.y, expandedRect.width, expandedRect.height, 3, 3);

        g.setFont(new Font("Arial", Font.BOLD, (int) (12 / t.getScaleX())));
        String message;
        if (lastResult != null)
            message = ((Result) lastResult.getResult()).getBarcodeFormat().toString() + "="
                    + getParsedCode(lastResult);
        else
            message = "UNRECOGNIZED!";
        g.drawString(message, rect.x, rect.y);

    } catch (Exception e) {
        logger.error("Unexpected errr while logging the image:", e);
    }

}

From source file:org.uva.itast.blended.omr.scanners.SolidSquareMarkScanner.java

/**
 * @param pageImage/*from   w w w  .  jav a 2  s  .com*/
 */
public void putEmphasisMarkOnImage(PageImage pageImage, Color color) {

    Graphics2D g = pageImage.getReportingGraphics();
    // int centerColor=imagen.getRGB(maxsimX, maxsimY);
    // g.setXORMode(new Color(centerColor));
    // g.setColor(Color.RED);
    // g.fillOval(maxsimX - markWidth/2, maxsimY - markHeight/2, markWidth,
    // markHeight);
    // g.setPaintMode();
    Dimension2D markDimsPx = pageImage.sizeInPixels(new Size(markWidth, markHeight));
    int markWidth = (int) markDimsPx.getWidth();
    int markHeight = (int) markDimsPx.getHeight();
    g.setColor(color);
    AffineTransform t = g.getTransform();
    g.drawLine(maxsimX, maxsimY - markHeight / 2 - 1, maxsimX,
            maxsimY - markHeight / 2 - (int) (20 / t.getScaleY()));
    Polygon arrowHead = new Polygon();
    arrowHead.addPoint(maxsimX, (int) (maxsimY - markHeight / 2 - 1 / t.getScaleY()));
    arrowHead.addPoint((int) (maxsimX - 6 / t.getScaleX()),
            (int) (maxsimY - markHeight / 2 - 6 / t.getScaleY()));
    arrowHead.addPoint((int) (maxsimX + 6 / t.getScaleX()),
            (int) (maxsimY - markHeight / 2 - 6 / t.getScaleY()));
    g.fillPolygon(arrowHead);

    g.setStroke(new BasicStroke(2, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
            new float[] { (float) (3 / t.getScaleX()), (float) (3 / t.getScaleY()) }, 0));
    g.drawRect(maxsimX - markWidth / 2 - 1, maxsimY - markHeight / 2 - 1, markWidth + 1, markHeight + 1);

}

From source file:statechum.analysis.learning.Visualiser.java

protected static PluggableRenderer constructRenderer(Graph g, final LayoutOptions options) {
    final LayoutOptions graphLayoutOptions = options != null ? options : new LayoutOptions();

    PluggableRenderer r = new PluggableRenderer() {
        /**//  w  w w  .  jav a 2  s. c o m
         * 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>.
         */
        @Override
        protected void drawSimpleEdge(Graphics2D g2d, Edge e, int x1, int y1, int x2, int y2) {
            final Vertex v1 = (Vertex) e.getEndpoints().getFirst();
            final Vertex v2 = (Vertex) e.getEndpoints().getSecond();
            boolean isLoop = v1.equals(v2);
            final Shape s2 = vertexShapeFunction.getShape(v2);
            Shape edgeShape = edgeShapeFunction.getShape(e);
            final double dx = x2 - x1;
            final double dy = y2 - y1;

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

            String label = edgeStringer.getLabel(e);
            assert (label != null);
            Component labelComponent = prepareRenderer(graphLabelRenderer, label, isPicked(e), e);
            Dimension d = labelComponent.getPreferredSize();
            Rectangle2D EdgeShapeBoundaries = edgeShape.getBounds2D();
            AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);
            double yMin = 0, yMax = 0;
            double thetaRadians = 0;
            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.
                int edgeIndex = ParallelEdgeIndexSingleton.getInstance().getIndex(e);
                Rectangle2D s2Bounds = s2.getBounds2D();
                double scaleBy = 1 + (graphLayoutOptions.scaleLines - 1) * 1. / 3.;
                double translation = s2Bounds.getHeight() * (1. / 4. + edgeIndex / 4.);

                xform.translate(0, -scaleBy * translation);
                xform.scale(scaleBy * s2Bounds.getWidth(), scaleBy * s2Bounds.getHeight());
                yMin = scaleBy * (EdgeShapeBoundaries.getMinY() * s2Bounds.getHeight()) - translation;
                yMax = scaleBy * (EdgeShapeBoundaries.getMaxY() * s2Bounds.getHeight()) - translation;

            } else {
                // this is a normal edge. Rotate it to the angle between
                // vertex endpoints, then scale it to the distance between
                // the vertices
                thetaRadians = Math.atan2(dy, dx);
                double dist = Math.sqrt(dx * dx + dy * dy);
                xform.rotate(thetaRadians);
                xform.scale(dist, 1.0);
                yMin = EdgeShapeBoundaries.getMinY();
                yMax = EdgeShapeBoundaries.getMaxY();
            }

            edgeShape = xform.createTransformedShape(edgeShape);
            // Debug code
            /*
            if (!isLoop)
            {
            g2d.setPaint(new Color( 250, 250, 0));
               AffineTransform rect = AffineTransform.getTranslateInstance(x1, y1+yMin);
               rect.rotate(thetaRadians);
               g2d.fill(rect.createTransformedShape(
              new Rectangle(0,0,(int)Math.sqrt(dx*dx + dy*dy),(int)(yMax-yMin))));
            }
            else
            {
            g2d.setPaint(new Color( 100, 250, 0));
            AffineTransform rect = AffineTransform.getTranslateInstance(x1-s2.getBounds2D().getWidth()/2, y1+yMin);
               rect.rotate(thetaRadians);
               g2d.fill(rect.createTransformedShape(
              new Rectangle(0,0,(int)s2.getBounds2D().getWidth(),(int)(yMax-yMin))));
            }*/

            edgeHit = viewTransformer.transform(edgeShape).intersects(deviceRectangle);

            if (edgeHit == true) {
                Paint oldPaint = g2d.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) {
                    g2d.setPaint(fill_paint);
                    g2d.fill(edgeShape);
                }
                Paint draw_paint = edgePaintFunction.getDrawPaint(e);
                if (draw_paint != null) {
                    g2d.setPaint(draw_paint);
                    g2d.draw(edgeShape);
                }

                double scalex = g2d.getTransform().getScaleX();
                double scaley = g2d.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
                        g2d.fill(arrow);
                    }
                    assert !(e instanceof UndirectedEdge);
                }

                // For difference visualisation only
                boolean labelBelow = false;
                if (graphLayoutOptions.showDIFF && (draw_paint == null
                        || draw_paint instanceof Color && ((Color) draw_paint).equals(Color.BLACK)))
                    labelBelow = true;

                // Now draw the label.
                double xLabel = 0, yLabel = 0, xa = 0, ya = 0, rotation = thetaRadians;
                if (isLoop) {
                    double displacementY = labelBelow ? -yMin + d.height : -yMin + d.height,
                            displacementX = d.width / 2;
                    xa = x1 + dx / 2 + displacementY * Math.sin(thetaRadians);
                    ya = y1 + dy / 2 - displacementY * Math.cos(thetaRadians);
                    xLabel = xa - displacementX * Math.cos(thetaRadians);
                    yLabel = ya - displacementX * Math.sin(thetaRadians);
                } else if (dx < 0) {
                    double displacementY = labelBelow ? yMax - d.height : (-yMax - d.height),
                            displacementX = d.width / 2;
                    xa = x1 + dx / 2 + displacementY * Math.sin(thetaRadians);
                    ya = y1 + dy / 2 - displacementY * Math.cos(thetaRadians);
                    xLabel = xa + displacementX * Math.cos(thetaRadians);
                    yLabel = ya + displacementX * Math.sin(thetaRadians);
                    rotation = thetaRadians + Math.PI;
                } else {
                    double displacementY = labelBelow ? yMax : -yMax, displacementX = d.width / 2;
                    xa = x1 + dx / 2 + displacementY * Math.sin(thetaRadians);
                    ya = y1 + dy / 2 - displacementY * Math.cos(thetaRadians);
                    xLabel = xa - displacementX * Math.cos(thetaRadians);
                    yLabel = ya - displacementX * Math.sin(thetaRadians);
                }

                AffineTransform old = g2d.getTransform();
                AffineTransform labelTransform = new AffineTransform();
                // Debug code: 
                //g2d.drawLine((int)(x1+dx/2), (int)(y1+dy/2), (int)(xa), (int)(ya));g2d.drawLine((int)(xa), (int)(ya), (int)(xLabel), (int)(yLabel));
                labelTransform.translate(xLabel, yLabel);
                labelTransform.rotate(rotation);
                g2d.setTransform(labelTransform);
                rendererPane.paintComponent(g2d, labelComponent, screenDevice, 0, 0, d.width, d.height, true);
                g2d.setTransform(old);

                // restore old paint
                g2d.setPaint(oldPaint);
            } // if edgeHit == true
        }
    };
    r = labelEdges(g, r, graphLayoutOptions);
    r = labelVertices(r, g, graphLayoutOptions);
    r.setVertexIncludePredicate(new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            if (!graphLayoutOptions.showIgnored && graphLayoutOptions.ignoredStates != null
                    && graphLayoutOptions.ignoredStates.contains(object.toString()))
                return false;

            if (graphLayoutOptions.showNegatives)
                return true;
            else
                return DeterministicDirectedSparseGraph.isAccept((Vertex) object);
        }
    });
    return r;
}

From source file:tufts.vue.LWComponent.java

/**
 * Useful for drawing drag images into an existing graphics buffer, or drawing exportable images.
 *
 * @param alpha 0.0 (invisible) to 1.0 (no alpha -- completely opaque)
 * @param maxSize max dimensions for image. May be null.  Image may be smaller than maxSize.
 * @param fillColor -- if non-null, will be rendered as background for image.
 * @param zoomRequest -- desired zoom; ignored if maxSize is non-null
 * also set, background fill will have transparency of alpha^3 to enhance contrast.
 */// w ww. jav  a 2s.  c o m

public void drawImage(Graphics2D g, double alpha, Dimension maxSize, Color fillColor, double zoomRequest) {
    //if (DEBUG.IMAGE) out("drawImage; size " + maxSize);

    final boolean drawBorder = false;// this instanceof LWMap; // hack for dragged images of LWMaps

    final Rectangle2D.Float bounds = getImageBounds();
    final Rectangle clip = g.getClipBounds();
    final Size fillSize = new Size(bounds);
    final double zoom = computeZoomAndSize(bounds, maxSize, zoomRequest, fillSize);

    if (DEBUG.IMAGE)
        out(TERM_GREEN + "drawImage:" + "\n\t   mapBounds: " + fmt(bounds) + "\n\t        fill: " + fillColor
                + "\n\t     maxSize: " + maxSize + "\n\t zoomRequest: " + zoomRequest + "\n\t     fitZoom: "
                + zoom + "\n\t    fillSize: " + fillSize + "\n\t          gc: " + g + "\n\t        clip: "
                + fmt(clip) + "\n\t       alpha: " + alpha + TERM_CLEAR);

    final int width = fillSize.pixelWidth();
    final int height = fillSize.pixelHeight();

    final DrawContext dc = new DrawContext(g, this);

    dc.setInteractive(false);

    if (alpha == OPAQUE) {
        dc.setPrintQuality();
    } else {
        // if alpha, assume drag image (todo: better specified as an argument)
        dc.setDraftQuality();
    }

    dc.setBackgroundFill(getRenderFillColor(null)); // sure we want null here?
    dc.setClipOptimized(false); // always draw all children -- don't bother to check bounds
    if (DEBUG.IMAGE)
        out(TERM_GREEN + "drawImage: " + dc + TERM_CLEAR);

    if (fillColor != null) {
        //             if (false && alpha != OPAQUE) {
        //                 Color c = fillColor;
        //                 // if we have an alpha and a fill, amplify the alpha on the background fill
        //                 // by changing the fill to one that has alpha*alpha, for a total of
        //                 // alpha*alpha*alpha given our GC already has an alpha set.
        //                 fillColor = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (alpha*alpha*255+0.5));
        //             }
        if (alpha != OPAQUE)
            dc.setAlpha(alpha, AlphaComposite.SRC); // erase any underlying in cache
        if (DEBUG.IMAGE)
            out("drawImage: fill=" + fillColor);
        g.setColor(fillColor);
        g.fillRect(0, 0, width, height);
    } else { //if (alpha != OPAQUE) {
        // we didn't have a fill, but we have an alpha: make sure any cached data is cleared
        // todo?: if fill is null, we need to clear as well -- it means we have implied alpha on any non-drawn bits
        // TODO: if this is a selection drag, we usually want to fill with the map color (or ideally, the color
        // of the common parent, e.g., a slide, if there's one common parent)
        dc.g.setComposite(AlphaComposite.Clear);
        g.fillRect(0, 0, width, height);
    }

    //if (alpha != OPAQUE)
    dc.setAlpha(alpha, AlphaComposite.SRC);

    if (DEBUG.IMAGE && DEBUG.META) {
        // Fill the entire imageable area
        g.setColor(Color.green);
        g.fillRect(0, 0, Short.MAX_VALUE, Short.MAX_VALUE);
    }

    final AffineTransform rawTransform = g.getTransform();

    if (zoom != 1.0)
        dc.g.scale(zoom, zoom);

    // translate so that the upper left corner of the map region
    // we're drawing is at 0,0 on the underlying image

    g.translate(-bounds.getX(), -bounds.getY());

    // GC *must* have a bounds set or we get NPE's in JComponent (textBox) rendering
    dc.setMasterClip(bounds);

    if (DEBUG.IMAGE && DEBUG.META) {
        // fill the clipped area so we can check our clip bounds
        dc.g.setColor(Color.red);
        dc.g.fillRect(-Short.MAX_VALUE / 2, -Short.MAX_VALUE / 2, // larger values than this can blow out internal GC code and we get nothing
                Short.MAX_VALUE, Short.MAX_VALUE);
    }

    if (this instanceof LWImage) {
        // for some reason, raw images don't seem to want to draw unless we fill first
        dc.g.setColor(Color.white);
        dc.g.fill(bounds);
    }

    // render to the image through the DrawContext/GC pointing to it
    draw(dc);

    if (drawBorder) {
        g.setTransform(rawTransform);
        //g.setColor(Color.red);
        //g.fillRect(0,0, Short.MAX_VALUE, Short.MAX_VALUE);
        if (DEBUG.IMAGE) {
            g.setColor(Color.black);
            dc.setAntiAlias(false);
        } else
            g.setColor(Color.darkGray);
        g.drawRect(0, 0, width - 1, height - 1);
    }

    if (DEBUG.IMAGE)
        out(TERM_GREEN + "drawImage: completed\n" + TERM_CLEAR);

}

From source file:uk.ac.babraham.BamQC.Graphs.ScatterGraph.java

@Override
protected void paintComponent(Graphics g) {

    g.setColor(Color.WHITE);//from w  ww .ja va2 s. com
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);

    if (g instanceof Graphics2D) {
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    double yStart, xStart;
    if (minY % yInterval == 0) {
        yStart = minY;
    } else {
        yStart = yInterval * (((int) minY / yInterval) + 1);
    }

    if (minX % xInterval == 0) {
        xStart = minX;
    } else {
        xStart = xInterval * (((int) minX / xInterval) + 1);
    }

    int xOffset = 0;

    // Draw the yLabel on the left of the yAxis
    int yLabelRightShift = 12;
    if (yLabel == null || yLabel.isEmpty()) {
        yLabelRightShift = 0;
    } else {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            AffineTransform orig = g2.getTransform();
            g2.rotate(-Math.PI / 2);
            g2.setColor(Color.BLACK);
            g2.drawString(yLabel, -getY(-yInterval) / 2 - (g.getFontMetrics().stringWidth(yLabel) / 2),
                    yLabelRightShift);
            g2.setTransform(orig);
        }
    }

    // Draw the y axis labels
    int lastYLabelEnd = Integer.MAX_VALUE;
    for (double i = yStart; i <= maxY; i += yInterval) {
        String label = "" + i;
        label = label.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int width = g.getFontMetrics().stringWidth(label);
        if (width > xOffset) {
            xOffset = width;
        }
        // place the y axis labels so that they don't overlap when the plot is resized.
        int baseNumberHeight = g.getFontMetrics().getHeight();
        int baseNumberPosition = getY(i) + (baseNumberHeight / 2);
        if (baseNumberPosition + baseNumberHeight < lastYLabelEnd) {
            // Draw the y axis labels
            g.drawString(label, yLabelRightShift + 6, baseNumberPosition);
            lastYLabelEnd = baseNumberPosition + 2;
        }
    }

    // Give the x axis a bit of breathing space
    xOffset = xOffset + yLabelRightShift + 8;

    // Now draw horizontal lines across from the y axis
    g.setColor(new Color(180, 180, 180));
    for (double i = yStart; i <= maxY; i += yInterval) {
        g.drawLine(xOffset, getY(i), getWidth() - 10, getY(i));
    }
    g.setColor(Color.BLACK);

    // Draw the graph title
    int titleWidth = g.getFontMetrics().stringWidth(graphTitle);
    g.drawString(graphTitle, (xOffset + ((getWidth() - (xOffset + 10)) / 2)) - (titleWidth / 2), 30);

    // Draw the xLabel under the xAxis
    g.drawString(xLabel, (getWidth() / 2) - (g.getFontMetrics().stringWidth(xLabel) / 2), getHeight() - 5);

    // Now draw the data points
    double baseWidth = (getWidth() - (xOffset + 10)) / (maxX - minX);

    //      System.out.println("Base Width is "+baseWidth);
    // Let's find the longest label, and then work out how often we can draw labels
    int lastXLabelEnd = 0;

    // Draw the x axis labels
    for (double i = xStart; i <= maxX; i += xInterval) {
        g.setColor(Color.BLACK);
        String baseNumber = "" + i;
        baseNumber = baseNumber.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int baseNumberWidth = g.getFontMetrics().stringWidth(baseNumber);
        int baseNumberPosition = (int) (xOffset + (baseWidth * i) - (baseNumberWidth / 2));

        if (baseNumberPosition > lastXLabelEnd) {
            g.drawString(baseNumber, baseNumberPosition, getHeight() - 25);
            lastXLabelEnd = baseNumberPosition + baseNumberWidth + 5;
        }
        // Now draw vertical lines across from the y axis
        g.setColor(new Color(180, 180, 180));
        g.drawLine((int) (xOffset + (baseWidth * i)), getHeight() - 40, (int) (xOffset + (baseWidth * i)), 40);
        g.setColor(Color.BLACK);
    }

    // Now draw the axes
    g.drawLine(xOffset, getHeight() - 40, getWidth() - 10, getHeight() - 40);
    g.drawLine(xOffset, getHeight() - 40, xOffset, 40);

    // Initialise the arrays containing the tooltips
    rectangles = new ArrayList<Rectangle>();
    tips = new ArrayList<String>();

    g.setColor(Color.BLUE);
    // Draw the data points
    double ovalSize = 5;
    // We distinguish two inputs since the x label does not start from 0.
    // used for computing the actual line points as if they were starting from 0.
    double[] inputVar = new double[data.length];
    double[] responseVar = new double[data.length];
    for (int d = 0; d < data.length; d++) {
        double x = getX(xCategories[d], xOffset) - ovalSize / 2;
        double y = getY(data[d]) - ovalSize / 2;
        g.fillOval((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        g.drawString(toolTipLabels[d], (int) x + 2, (int) y + 16);
        inputVar[d] = Double.valueOf(xCategories[d]);
        responseVar[d] = data[d];

        // Tool tips
        Rectangle r = new Rectangle((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        rectangles.add(r);
        tips.add(toolTipLabels[d]);
    }
    g.setColor(Color.BLACK);

    // Draw the intercept 

    // WARNING: Is drawing a least squares regression line asserting that "the distribution follows a power law" correct?
    // This is our case if we plot log-log..
    // It seems not in this paper (Appendix A) http://arxiv.org/pdf/0706.1062v2.pdf

    if (data.length > 1) {
        LinearRegression linReg = new LinearRegression(inputVar, responseVar);
        double intercept = linReg.intercept();
        double slope = linReg.slope();
        double rSquare = linReg.R2();

        // Let's now calculate the two points (x1, y1) and (xn, yn)
        // (x1, y1). We need to skip the areas where x1<minY and y1>maxY
        double x1 = minX;
        double y1 = slope * minX + intercept;
        if (y1 < minY) {
            x1 = (minY - intercept) / slope;
            y1 = minY;
        } else if (y1 > maxY) {
            x1 = (maxY - intercept) / slope;
            y1 = maxY;
        }
        // (xn, yn). maxX which essentially is inputVar[inputVar.length-1]
        double xn = maxX;
        double yn = slope * maxX + intercept;

        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1.5f));
        }
        g.setColor(Color.RED);
        g.drawLine(getX(x1, xOffset), getY(y1), getX(xn, xOffset), getY(yn));
        g.setColor(Color.BLACK);
        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1));
        }

        // Draw the legend for the intercept
        String legendString = "y = " + Precision.round(slope, 3) + "x";
        if (intercept < 0)
            legendString += " - " + Precision.round(-intercept, 3);
        else
            legendString += " + " + Precision.round(intercept, 3);
        int width = g.getFontMetrics().stringWidth(legendString);

        // First draw a box to put the legend in
        g.setColor(Color.WHITE);
        g.fillRect(xOffset + 10, 45, width + 8, 35);
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(xOffset + 10, 45, width + 8, 35);

        // Now draw the legend label
        g.setColor(Color.RED);
        g.drawString(legendString, xOffset + 13, 60);
        g.drawString("R^2 = " + Precision.round(rSquare, 3), xOffset + 13, 76);
        g.setColor(Color.BLACK);
    }

}

From source file:util.ui.UiUtilities.java

/**
 * Scales Icons to a specific size/*from w w  w. j ava 2 s  .  co  m*/
 *
 * @param icon
 *          Icon that should be scaled
 * @param width
 *          scaled width
 * @param height
 *          scaled height
 * @return Scaled Icon
 */
public static Icon scaleIcon(Icon icon, int width, int height) {
    if (icon == null) {
        return null;
    }
    int currentWidth = icon.getIconWidth();
    int currentHeight = icon.getIconHeight();
    if ((currentWidth == width) && (currentHeight == height)) {
        return icon;
    }
    try {
        // Create Image with Icon
        BufferedImage iconImage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = iconImage.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        AffineTransform z = g2.getTransform();
        g2.setTransform(z);
        icon.paintIcon(null, g2, 0, 0);
        g2.dispose();
        BufferedImage scaled = scaleDown(iconImage, width, height);
        // Return new Icon
        return new ImageIcon(scaled);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return icon;
}

From source file:VASSAL.counters.Labeler.java

public void draw(Graphics g, int x, int y, Component obs, double zoom) {
    updateCachedImage();/*from w w w. jav  a2s.c om*/
    piece.draw(g, x, y, obs, zoom);

    // FIXME: We should be drawing the text at the right size, not scaling it!
    final Point p = getLabelPosition();
    final int labelX = x + (int) (zoom * p.x);
    final int labelY = y + (int) (zoom * p.y);

    AffineTransform saveXForm = null;
    final Graphics2D g2d = (Graphics2D) g;

    if (rotateDegrees != 0) {
        saveXForm = g2d.getTransform();
        final AffineTransform newXForm = AffineTransform.getRotateInstance(Math.toRadians(rotateDegrees), x, y);
        g2d.transform(newXForm);
    }

    imagePainter.draw(g, labelX, labelY, zoom, obs);

    if (rotateDegrees != 0) {
        g2d.setTransform(saveXForm);
    }
}