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:ucar.unidata.idv.control.chart.ChartAnnotation.java

/**
 * Called by base classes when drawn. We set the transform here
 *
 * @param g2 The graphics/*  w w w  . j  a  v a 2 s  .  co m*/
 */
protected void setGraphicsState(Graphics2D g2) {
    transform = g2.getTransform();
}

From source file:gda.plots.SimpleLegendGraphic.java

/**
 * Overrides the super class method but is the same except that it creates a SimpleLegendEntity for itself and then
 * returns a non-null BlockResult containing the entity.
 * //  ww w .ja  va2  s.c om
 * @param g2
 *            the Graphics2D to use
 * @param area
 *            the area to draw in
 * @param params
 *            ignored
 * @return a BlockResult containing a StandardEntityCollection containing the SimpleLegendEntity
 */
@Override
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {

    draw(g2, area);

    ChartEntity entity = null;
    // This was written by looking at what happens in LabelBlock's draw
    // method. The area has to be transformed into the actual coordinates
    // of the overall ChartPanel for the MouseEvents to work properly.
    entity = new SimpleLegendEntity(g2.getTransform().createTransformedShape(area), sxys.getName(), null, sxys);

    BlockResult result = new BlockResult();
    StandardEntityCollection sec = new StandardEntityCollection();
    sec.add(entity);
    result.setEntityCollection(sec);
    return result;
}

From source file:GrafosTroleBus.java

public GrafosTroleBus() {
    setLayout(new BorderLayout());

    //definir puntos de trolebus (latitude y longitude) @autor sa

    map.put("RECREO", new String[] { "-0.2516682", "-78.521524" }); //Recreo                       
    map.put("P14", new String[] { "-0.2445098", "-78.51902" }); //Villaflora
    map.put("P15", new String[] { "-0.2396436", "-78.51698" }); //Chimbacalle N-S                      
    map.put("P16", new String[] { "-0.2378458", "-78.515976" }); //Chimbacalle S-N
    map.put("P17", new String[] { "-0.2356805", "-78.514816" }); //Colina
    map.put("P18", new String[] { "-0.234052", "-78.514237" }); //Jefferson Perez
    map.put("P19", new String[] { "-0.2312856", "-78.513627" }); //Recoleta N-S        
    map.put("P20", new String[] { "-0.2307005", "-78.513051" }); //Recoleta S-N
    map.put("P21", new String[] { "-0.2263919", "-78.513011" }); //P21 Cumanda N-S
    map.put("P22", new String[] { "-0.226424", "-78.512803" }); //P22 Cumanda S-N
    map.put("P23", new String[] { "-0.2234658", "-78.512542" }); //P23 Santo Domingo
    map.put("P24", new String[] { "-0.2185857", "-78.508601" }); //P24 Plaza del Teatro N-S
    map.put("P25", new String[] { "-0.219605", "-78.50813" }); //P25 Plaza del Teatro S-N        
    map.put("P26", new String[] { "-0.2177808", "-78.505977" }); //P26 Hermano Miguel
    map.put("P27", new String[] { "-0.2169088", "-78.50521" }); //P27 Banco Central
    map.put("P28", new String[] { "-0.214267", "-78.502999" }); //P28 La Alameda S-N
    map.put("P29", new String[] { "-0.2137705", "-78.50293" }); //P29 La Alameda N-S                       
    map.put("P30", new String[] { "-0.2084939", "-78.500255" }); //P30 Ejido N-S
    map.put("P31", new String[] { "-0.2088076", "-78.500032" }); //P31 Ejido S-N
    map.put("P32", new String[] { "-0.2047989", "-78.4988" }); //P32 La Mariscal N-S
    map.put("P33", new String[] { "-0.2041972", "-78.498491" }); //P33 La Mariscal S-N
    map.put("P34", new String[] { "-0.2009718", "-78.49715" }); //P34 Santa Clara S-N
    map.put("P35", new String[] { "-0.201056", "-78.496979" }); //P35 Santa Clara N-S
    map.put("P36", new String[] { "-0.1986325", "-78.496141" }); //P36 La Colon S-N
    map.put("P37", new String[] { "-0.1978432", "-78.495563" }); //P37 La Colon N-S
    map.put("P38", new String[] { "-0.1921587", "-78.493445" }); //P38 Cuero y Caicedo S-N
    map.put("P39", new String[] { "-0.1915098", "-78.493001" }); //P39 Cuero y Caicedo N-S                        
    map.put("P40", new String[] { "-0.1889467", "-78.492149" }); //P40 Mariana de Jess S-N
    map.put("P41", new String[] { "-0.1875567", "-78.491303" }); //P41 Mariana de Jesus N-S
    map.put("P42", new String[] { "-0.1853693", "-78.490878" }); //P42 El Floron S-N
    map.put("P43", new String[] { "-0.1846687", "-78.490403" }); //P43 El Floron N-S        
    map.put("P44", new String[] { "-0.1817679", "-78.489808" }); //P44 Carolina S-N
    map.put("P45", new String[] { "-0.1810849", "-78.489336" }); //P45 Carolina N-S
    map.put("P46", new String[] { "-0.1787274", "-78.488954" }); //P46 Estadio S-N
    map.put("P47", new String[] { "-0.1780172", "-78.488621" }); //P47 Estadio N-S
    map.put("P48", new String[] { "-0.172087", "-78.487589" }); //P48 La Y S-N
    map.put("P49", new String[] { "-0.1713146", "-78.487277" }); //P49 La Y N-S        
    map.put("LA Y", new String[] { "-0.1635504", "-78.485374" }); //Estacin La Y                              

    nodoList = new ArrayList<String>(map.keySet());

    // create a simple graph for the demo        
    graph = new DirectedSparseMultigraph<String, Number>();
    createVertices();/*from  www  . j av a  2 s .  c  o  m*/
    createEdges();

    ImageIcon mapIcon = null;
    String imageLocation = "/mapa_quito.png";

    try {
        mapIcon = new ImageIcon(getClass().getResource(imageLocation));

        ImageWidth = mapIcon.getIconWidth();
        ImageHeight = mapIcon.getIconHeight();

    } catch (Exception ex) {
        System.err.println("Can't load \"" + imageLocation + "\"");
    }

    final ImageIcon icon = mapIcon;

    Dimension layoutSize = new Dimension(ImageWidth, ImageHeight);

    Layout<String, Number> layout = new StaticLayout<String, Number>(graph,
            new ChainedTransformer<String, Point2D>(new Transformer[] { new CityTransformer(map),
                    new LatLonPixelTransformer(new Dimension(ImageWidth, ImageHeight)) }));

    layout.setSize(layoutSize);
    vv = new VisualizationViewer<String, Number>(layout, new Dimension(MonitorWidth, MonitorHeight));

    if (icon != null) {
        vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {
            public void paint(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                AffineTransform oldXform = g2d.getTransform();
                AffineTransform lat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.LAYOUT).getTransform();
                AffineTransform vat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.VIEW).getTransform();
                AffineTransform at = new AffineTransform();
                at.concatenate(g2d.getTransform());
                at.concatenate(vat);
                at.concatenate(lat);
                g2d.setTransform(at);
                g.drawImage(icon.getImage(), 0, 0, icon.getIconWidth(), icon.getIconHeight(), vv);
                g2d.setTransform(oldXform);
            }

            public boolean useTransform() {
                return false;
            }
        });
    }

    vv.getRenderer().setVertexRenderer(new GradientVertexRenderer<String, Number>(Color.white, Color.red,
            Color.white, Color.blue, vv.getPickedVertexState(), false));

    // add my listeners for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());
    vv.setEdgeToolTipTransformer(new Transformer<Number, String>() {
        public String transform(Number edge) {
            return "E" + graph.getEndpoints(edge).toString();
        }
    });

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderer().getVertexLabelRenderer().setPositioner(new InsidePositioner());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    add(panel);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse<Object, Object>();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());
    vv.setToolTipText("<html><center>Type 'p' for Pick mode<p>Type 't' for Transform mode");

    final ScalingControl scaler = new CrossoverScalingControl();

    vv.scaleToLayout(scaler);

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    add(controls, BorderLayout.SOUTH);
}

From source file:TextRendering.java

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

    Dimension d = getSize();/* ww  w  . j  av  a 2s  .co m*/
    AffineTransform ct = AffineTransform.getTranslateInstance(d.width / 2, d.height * 3 / 4);
    g2.transform(ct);

    String s = "www.java2s.com";
    Font f = new Font("Serif", Font.PLAIN, 128);
    g2.setFont(f);

    int count = 6;
    for (int i = 1; i <= count; i++) {
        AffineTransform oldTransform = g2.getTransform();

        float ratio = (float) i / (float) count;
        g2.transform(AffineTransform.getRotateInstance(Math.PI * (ratio - 1.0f)));
        float alpha = ((i == count) ? 1.0f : ratio / 3);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.drawString(s, 0, 0);

        g2.setTransform(oldTransform);
    }
}

From source file:SWT2D.java

private void run() {
    // Create top level shell
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Java 2D Example");
    // GridLayout for canvas and button
    shell.setLayout(new GridLayout());
    // Create container for AWT canvas
    final Composite canvasComp = new Composite(shell, SWT.EMBEDDED);
    // Set preferred size
    GridData data = new GridData();
    data.widthHint = 600;//w  ww  .  jav  a 2 s .  co  m
    data.heightHint = 500;
    canvasComp.setLayoutData(data);
    // Create AWT Frame for Canvas
    java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp);
    // Create Canvas and add it to the Frame
    final java.awt.Canvas canvas = new java.awt.Canvas();
    canvasFrame.add(canvas);
    // Get graphical context and cast to Java2D
    final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas.getGraphics();
    // Enable antialiasing
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Remember initial transform
    final java.awt.geom.AffineTransform origTransform = g2d.getTransform();
    // Create Clear button and position it
    Button clearButton = new Button(shell, SWT.PUSH);
    clearButton.setText("Clear");
    data = new GridData();
    data.horizontalAlignment = GridData.CENTER;
    clearButton.setLayoutData(data);
    // Event processing for Clear button
    clearButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            // Delete word list and redraw canvas
            wordList.clear();
            canvasComp.redraw();
        }
    });
    // Process canvas mouse clicks
    canvas.addMouseListener(new java.awt.event.MouseListener() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
        }

        public void mouseEntered(java.awt.event.MouseEvent e) {
        }

        public void mouseExited(java.awt.event.MouseEvent e) {
        }

        public void mousePressed(java.awt.event.MouseEvent e) {
            // Manage pop-up editor
            display.syncExec(new Runnable() {
                public void run() {
                    if (eShell == null) {
                        // Create new Shell: non-modal!
                        eShell = new Shell(shell, SWT.NO_TRIM | SWT.MODELESS);
                        eShell.setLayout(new FillLayout());
                        // Text input field
                        eText = new Text(eShell, SWT.BORDER);
                        eText.setText("Text rotation in the SWT?");
                        eShell.pack();
                        // Set position (Display coordinates)
                        java.awt.Rectangle bounds = canvas.getBounds();
                        org.eclipse.swt.graphics.Point pos = canvasComp.toDisplay(bounds.width / 2,
                                bounds.height / 2);
                        Point size = eShell.getSize();
                        eShell.setBounds(pos.x, pos.y, size.x, size.y);
                        // Open Shell
                        eShell.open();
                    } else if (!eShell.isVisible()) {
                        // Editor versteckt, sichtbar machen
                        eShell.setVisible(true);
                    } else {
                        // Editor is visible - get text
                        String t = eText.getText();
                        // set editor invisible
                        eShell.setVisible(false);
                        // Add text to list and redraw canvas
                        wordList.add(t);
                        canvasComp.redraw();
                    }
                }
            });
        }

        public void mouseReleased(java.awt.event.MouseEvent e) {
        }
    });
    // Redraw the canvas
    canvasComp.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            // Pass the redraw task to AWT event queue
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    // Compute canvas center
                    java.awt.Rectangle bounds = canvas.getBounds();
                    int originX = bounds.width / 2;
                    int originY = bounds.height / 2;
                    // Reset canvas
                    g2d.setTransform(origTransform);
                    g2d.setColor(java.awt.Color.WHITE);
                    g2d.fillRect(0, 0, bounds.width, bounds.height);
                    // Set font
                    g2d.setFont(new java.awt.Font("Myriad", java.awt.Font.PLAIN, 32));
                    double angle = 0d;
                    // Prepare star shape
                    double increment = Math.toRadians(30);
                    Iterator iter = wordList.iterator();
                    while (iter.hasNext()) {
                        // Determine text colors in RGB color cycle
                        float red = (float) (0.5 + 0.5 * Math.sin(angle));
                        float green = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(120)));
                        float blue = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(240)));
                        g2d.setColor(new java.awt.Color(red, green, blue));
                        // Redraw text
                        String text = (String) iter.next();
                        g2d.drawString(text, originX + 50, originY);
                        // Rotate for next text output
                        g2d.rotate(increment, originX, originY);
                        angle += increment;
                    }
                }
            });
        }
    });
    // Finish shell and open it
    shell.pack();
    shell.open();
    // SWT event processing
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:FontPaint.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);/*from   w  ww .  j  av a 2 s .c om*/
    int width = getSize().width;
    int height = getSize().height;
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, 60);
    String s = new String("Java Source and Support.");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle outlineBounds = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(width / 2 - (outlineBounds.width / 2), height / 2 + (outlineBounds.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
}

From source file:com.net2plan.gui.utils.topologyPane.jung.JUNGCanvas.java

public void updateBackgroundImage(final ImageIcon icon, final int x, final int y) {
    if (paintableAssociatedToBackgroundImage != null)
        vv.removePreRenderPaintable(paintableAssociatedToBackgroundImage);
    paintableAssociatedToBackgroundImage = null;
    if (icon != null) {
        this.paintableAssociatedToBackgroundImage = new VisualizationViewer.Paintable() {
            public void paint(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                AffineTransform oldXform = g2d.getTransform();
                AffineTransform lat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.LAYOUT).getTransform();
                AffineTransform vat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.VIEW).getTransform();
                AffineTransform at = new AffineTransform();
                at.concatenate(g2d.getTransform());
                at.concatenate(vat);//w  ww  .j  av  a 2  s. c  om
                at.concatenate(lat);
                g2d.setTransform(at);
                g.drawImage(icon.getImage(), x, y, icon.getIconWidth(), icon.getIconHeight(), vv);
                g2d.setTransform(oldXform);
            }

            public boolean useTransform() {
                return false;
            }
        };
        vv.addPreRenderPaintable(paintableAssociatedToBackgroundImage);
    }
}

From source file:com.liusoft.dlog4j.action.PhotoAction.java

/**
 * //from ww  w  .j  a  v  a  2 s.c om
 * @param ctx
 * @param imgURL
 * @param orient
 * @return
 * @throws IOException
 */
protected boolean rotate(HttpContext ctx, String imgURL, int orient) throws IOException {
    PhotoSaver saver = this.getPhotoSaver();
    InputStream inImg = saver.read(ctx, imgURL);
    BufferedImage old_img = (BufferedImage) ImageIO.read(inImg);
    int width = old_img.getWidth();
    int height = old_img.getHeight();
    BufferedImage new_img = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = new_img.createGraphics();

    AffineTransform origXform = g2d.getTransform();
    AffineTransform newXform = (AffineTransform) (origXform.clone());
    // center of rotation is center of the panel
    double radian = 0;
    double xRot = 0;
    double yRot = 0;
    switch (orient) {
    case 3:
        radian = 180.0;
        xRot = width / 2.0;
        yRot = height / 2.0;
    case 6:
        radian = 90.0;
        xRot = height / 2.0;
        yRot = xRot;
        break;
    case 8:
        radian = 270.0;
        xRot = width / 2.0;
        yRot = xRot;
        break;
    default:
        return false;
    }
    newXform.rotate(Math.toRadians(radian), xRot, yRot);

    g2d.setTransform(newXform);
    // draw image centered in panel
    g2d.drawImage(old_img, 0, 0, null);
    // Reset to Original
    g2d.setTransform(origXform);
    OutputStream out = saver.write(ctx, imgURL);
    try {
        ImageIO.write(new_img, "JPG", out);
    } finally {
        out.close();
    }
    return true;
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {//from   ww  w.j av a  2  s .c o m
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Starry.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);//from   w  ww .  java 2  s . c om
    w = getSize().width;
    h = getSize().height;
    Graphics2D g2;
    g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, w / 10);
    String s = new String("The Starry Night");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle r = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(w / 2 - (r.width / 2), h / 2 + (r.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
    g2.drawImage(img, r.x, r.y, r.width, r.height, this);

}