Java Code Examples for java.awt.Graphics2D#translate()

The following examples show how to use java.awt.Graphics2D#translate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: triplea   File: MapPanel.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void drawTiles(
    final Graphics2D g,
    final List<Tile> images,
    final Rectangle2D.Double bounds,
    final List<Tile> undrawn) {
  g.translate(-bounds.getX(), -bounds.getY());
  for (final Tile tile : tileManager.getTiles(bounds)) {
    if (tile.needsRedraw()) {
      // take what we can get to avoid screen flicker
      undrawn.add(tile);
    } else {
      images.add(tile);
    }
    g.drawImage(tile.getImage(), tile.getBounds().x, tile.getBounds().y, this);
  }
  g.translate(bounds.getX(), bounds.getY());
}
 
Example 2
public void runTest(Object ctx, int numReps) {
    DrawEllipse2Ds.Context cctx = (DrawEllipse2Ds.Context) ctx;
    int size = cctx.size;
    int x = cctx.initX;
    int y = cctx.initY;
    Ellipse2D ellipse = cctx.ellipse;
    Graphics2D g2d = (Graphics2D) cctx.graphics;
    g2d.translate(cctx.orgX, cctx.orgY);
    Color rCArray[] = cctx.colorlist;
    int ci = cctx.colorindex;
    do {
        if (rCArray != null) {
            g2d.setColor(rCArray[ci++ & NUM_RANDOMCOLORMASK]);
        }
        ellipse.setFrame(x, y, size, size);
        g2d.draw(ellipse);
        if ((x -= 3) < 0) x += cctx.maxX;
        if ((y -= 1) < 0) y += cctx.maxY;
    } while (--numReps > 0);
    cctx.colorindex = ci;
    g2d.translate(-cctx.orgX, -cctx.orgY);
}
 
Example 3
Source Project: Java8CN   File: ShapeGraphicAttribute.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void draw(Graphics2D graphics, float x, float y) {

    // translating graphics to draw Shape !!!
    graphics.translate((int)x, (int)y);

    try {
        if (fStroke == STROKE) {
            // REMIND: set stroke to correct size
            graphics.draw(fShape);
        }
        else {
            graphics.fill(fShape);
        }
    }
    finally {
        graphics.translate(-(int)x, -(int)y);
    }
}
 
Example 4
/**
 * Paints the arrow panel.
 *
 * @param g  the graphics device for drawing on.
 */
public void paintComponent(final Graphics g) {

    super.paintComponent(g);
    final Graphics2D g2 = (Graphics2D) g;

    // first determine the size of the drawing area...
    final Dimension size = getSize();
    final Insets insets = getInsets();
    this.available.setRect(insets.left, insets.top,
                           size.getWidth() - insets.left - insets.right,
                           size.getHeight() - insets.top - insets.bottom);
    g2.translate(insets.left, insets.top);
    g2.fill(getArrow(this.type));

}
 
Example 5
/**
 *
 * @param mols
 * @param cellCanvas
 * @param g
 */
public void layout(
        List<IAtomContainer> mols, Dimension cellCanvas, Graphics2D g) {
    AffineTransform originalTransform = g.getTransform();
    double w = cellCanvas.width;
    double h = cellCanvas.height;

    double centerX = w / 2;
    double centerY = h / 2;
    int colCounter = 1;
    for (IAtomContainer mol : mols) {
        double zoom = calculateZoom(mol, cellCanvas);
        g.translate(centerX, centerY);
        g.scale(zoom, zoom);
        drawer.drawMolecule(mol, g);
        g.setTransform(originalTransform);
        if (colCounter < cols) {
            centerX += w;
            colCounter++;
        } else {
            centerY += h;
            centerX = w / 2;
            colCounter = 1;
        }
    }
}
 
Example 6
public void runTest(Object ctx, int numReps) {
    DrawEllipse2Ds.Context cctx = (DrawEllipse2Ds.Context) ctx;
    int size = cctx.size;
    int x = cctx.initX;
    int y = cctx.initY;
    Ellipse2D ellipse = cctx.ellipse;
    Graphics2D g2d = (Graphics2D) cctx.graphics;
    g2d.translate(cctx.orgX, cctx.orgY);
    Color rCArray[] = cctx.colorlist;
    int ci = cctx.colorindex;
    do {
        if (rCArray != null) {
            g2d.setColor(rCArray[ci++ & NUM_RANDOMCOLORMASK]);
        }
        ellipse.setFrame(x, y, size, size);
        g2d.draw(ellipse);
        if ((x -= 3) < 0) x += cctx.maxX;
        if ((y -= 1) < 0) y += cctx.maxY;
    } while (--numReps > 0);
    cctx.colorindex = ci;
    g2d.translate(-cctx.orgX, -cctx.orgY);
}
 
Example 7
Source Project: ramus   File: TableColumn.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void paint(Graphics2D g, Bounds bounds, Diagram diagram) {
    QBounds qBounds = (QBounds) bounds;
    columnHeader.paint(g, createHeaderBounds(qBounds), diagram);
    g.translate(0, 35);
    columnBody.paint(g, createBodyBounds(qBounds), diagram);
    g.translate(0, -35);
    g.draw(new Line2D.Double(0, 0, 0, height));
}
 
Example 8
Source Project: Bytecoder   File: BasicArrowButton.java    License: Apache License 2.0 5 votes vote down vote up
private void paintScaledTriangle(Graphics g, double x, double y, double size,
                                 int direction, boolean isEnabled) {
    size = Math.max(size, 2);
    Path2D.Double path = new Path2D.Double();
    path.moveTo(-size, size / 2);
    path.lineTo(size, size / 2);
    path.lineTo(0, -size / 2);
    path.closePath();
    AffineTransform affineTransform = new AffineTransform();
    affineTransform.rotate(Math.PI * (direction - 1) / 4);
    path.transform(affineTransform);

    Graphics2D g2d = (Graphics2D) g;
    double tx = x + size / 2;
    double ty = y + size / 2;
    g2d.translate(tx, ty);
    Color oldColor = g.getColor();
    if (!isEnabled) {
        g2d.translate(1, 0);
        g2d.setColor(highlight);
        g2d.fill(path);
        g2d.translate(-1, 0);
    }
    g2d.setColor(isEnabled ? darkShadow : shadow);
    g2d.fill(path);
    g2d.translate(-tx, -ty);
    g2d.setColor(oldColor);
}
 
Example 9
public void render(Graphics2D g) {
	if (location.x != 0 && location.y != 0) {
		g.translate(location.x, location.y);
		g.draw(area);
		g.translate(-location.x, -location.y);
	} else {
		g.draw(area);
	}
}
 
Example 10
public void runTest(Object ctx, int numReps) {
    DrawCubics.Context cctx = (DrawCubics.Context) ctx;
    int size = cctx.size;
    // Note: 2x2 ends up hitting exactly 1 pixel...
    if (size < 2) size = 2;
    int x = cctx.initX;
    int y = cctx.initY;
    int cpoffset = (int) (size/relYmax/2);
    CubicCurve2D curve = cctx.curve;
    Graphics2D g2d = (Graphics2D) cctx.graphics;
    g2d.translate(cctx.orgX, cctx.orgY);
    Color rCArray[] = cctx.colorlist;
    int ci = cctx.colorindex;
    do {
        curve.setCurve(x, y+size/2.0,
                       x+size/2.0, y+size/2.0-cpoffset,
                       x+size/2.0, y+size/2.0+cpoffset,
                       x+size, y+size/2.0);

        if (rCArray != null) {
            g2d.setColor(rCArray[ci++ & NUM_RANDOMCOLORMASK]);
        }
        g2d.draw(curve);
        if ((x -= 3) < 0) x += cctx.maxX;
        if ((y -= 1) < 0) y += cctx.maxY;
    } while (--numReps > 0);
    cctx.colorindex = ci;
    g2d.translate(-cctx.orgX, -cctx.orgY);
}
 
Example 11
public void render(Graphics g, int w, int h) {
    initImages(w, h);

    g.setColor(new Color(0xAD, 0xD8, 0xE6));
    g.fillRect(0, 0, w, h);

    Graphics2D g2d = (Graphics2D) g.create();
    for (Image im : images) {
        g2d.drawImage(im, 0, 0, null);
        g2d.translate(0, im.getHeight(null));
    }
}
 
Example 12
static void testAll(Graphics2D g2d) {
    g2d.setTransform(identity);
    g2d.translate(100, 100);
    testPrimitives(g2d);

    g2d.setTransform(identity);
    g2d.scale(10, 10);
    testPrimitives(g2d);

    g2d.setTransform(identity);
    g2d.rotate(Math.PI/6);
    testPrimitives(g2d);
}
 
Example 13
/**
 * Draws the image.
 *
 * @param panel  the world in which the arrow is viewed
 * @param g  the graphics context upon which to draw
 */
public void draw(DrawingPanel panel, Graphics g) {
  toPixels = panel.getPixelTransform();
  Point2D pt = new Point2D.Double(x, y);
  pt = toPixels.transform(pt, pt);
  Graphics2D g2 = (Graphics2D) g;
  g2.translate(pt.getX(), pt.getY());
  AffineTransform trans = new AffineTransform();
  trans.translate(-width/2, -height/2);
  trans.rotate(-theta, width/2, height/2);
  trans.scale(width/image.getWidth(null), height/image.getHeight(null));
  g2.drawImage(image, trans, null);
  g2.translate(-pt.getX(), -pt.getY());
}
 
Example 14
Source Project: hottub   File: CSSBorder.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void paintBorder(Component c, Graphics g,
                                    int x, int y, int width, int height) {
    if (!(g instanceof Graphics2D)) {
        return;
    }

    Graphics2D g2 = (Graphics2D) g.create();

    int[] widths = getWidths();

    // Position and size of the border interior.
    int intX = x + widths[LEFT];
    int intY = y + widths[TOP];
    int intWidth = width - (widths[RIGHT] + widths[LEFT]);
    int intHeight = height - (widths[TOP] + widths[BOTTOM]);

    // Coordinates of the interior corners, from NW clockwise.
    int[][] intCorners = {
        { intX, intY },
        { intX + intWidth, intY },
        { intX + intWidth, intY + intHeight },
        { intX, intY + intHeight, },
    };

    // Draw the borders for all sides.
    for (int i = 0; i < 4; i++) {
        Value style = getBorderStyle(i);
        Polygon shape = getBorderShape(i);
        if ((style != Value.NONE) && (shape != null)) {
            int sideLength = (i % 2 == 0 ? intWidth : intHeight);

            // "stretch" the border shape by the interior area dimension
            shape.xpoints[2] += sideLength;
            shape.xpoints[3] += sideLength;
            Color color = getBorderColor(i);
            BorderPainter painter = getBorderPainter(i);

            double angle = i * Math.PI / 2;
            g2.setClip(g.getClip()); // Restore initial clip
            g2.translate(intCorners[i][0], intCorners[i][1]);
            g2.rotate(angle);
            g2.clip(shape);
            painter.paint(shape, g2, color, i);
            g2.rotate(-angle);
            g2.translate(-intCorners[i][0], -intCorners[i][1]);
        }
    }
    g2.dispose();
}
 
Example 15
Source Project: mars-sim   File: LightBulb.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
  protected void paintComponent(Graphics g) {
      // Create the Graphics2D object
      final Graphics2D G2 = (Graphics2D) g.create();

      // Set the rendering hints
      G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
G2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      G2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
      G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);

      // Take direction into account
      switch (direction) {
          case SwingUtilities.SOUTH:
              G2.rotate(Math.PI, CENTER.getX(), CENTER.getY());
              break;
          case SwingUtilities.EAST:
              G2.rotate(-Math.PI / 2, CENTER.getX(), CENTER.getY());
              break;
          case SwingUtilities.WEST:
              G2.rotate(Math.PI / 2, CENTER.getX(), CENTER.getY());
              break;
      }

      // Take insets into account (e.g. used by borders)
      G2.translate(getInnerBounds().x, getInnerBounds().y);

      if (on) {
          G2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f - alpha));
          G2.drawImage(offImage, 0, 0, null);
          G2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
          G2.drawImage(onImage, 0, 0, null);
          G2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
      } else {
          G2.drawImage(offImage, 0, 0, null);
      }
      G2.drawImage(bulbImage, 0, 0, null);

      // Dispose the temp graphics object
      G2.dispose();
  }
 
Example 16
@Override
public void paintIcon(Component c, Graphics g0, int x, int y) {
    final double thisPaintScale = getScaling(((Graphics2D) g0).getTransform());
    final double toolkitScale = Toolkit.getDefaultToolkit().getScreenResolution() / 96.0;
    /* When the delegate (incorrectly) changes its reported icon width, it also paints the icon
    correspondingly larger or smaller. We must take this behavior into account to know the
    actual dimensions painted by the delegate. Note that once the bug in WindowsIconFactory is
    fixed, this factor will just always be 1.0, and no harm should come from this logic. */
    final double iconSizeChangeFactor;
    {
        /* The width and height of the delegate icon comes from the native GetThemePartSize
        function in the Windows API. It seems to always be consistent with the size of the
        bitmap that will be drawn by DrawThemeBackground. (Once JDK-8211715 is fixed,
        getIconWidth()/getIconHeight() should never change from its value when the application
        was first started.) */
        final double currentWidth = delegate.getIconWidth();
        final double currentHeight = delegate.getIconHeight();
        /* Try to find the original, even scaling factor that caused width/height to be enlarged
        or shrunk to currentWidth/currentHeight. This is tricky because we only know the values
        of currentWidth/currentHeight after rounding. Find a lower and upper bound of the actual
        scaling factor when taking possible rounding errors into account. */
        double lowerBound = Math.max(
                (currentWidth - 1.0) / (double) width,
                (currentHeight - 1.0) / (double) height);
        double upperBound = Math.min(
                (currentWidth + 1.0) / (double) width,
                (currentHeight + 1.0) / (double) height);
        /* See if the scaling factor might be one of a few possible even fractions. This can
        help avoid scaling artifacts when painting the backbuffer image to the paintIcon
        Graphics. */
        double average = (lowerBound + upperBound) / 2.0;
        List<Double> candidateScales = new ArrayList<>();
        candidateScales.add(roundToNearestMultiple(thisPaintScale / toolkitScale, 0.25));
        candidateScales.add(toolkitScale);
        candidateScales.add(1.0 / toolkitScale);
        candidateScales.add(roundToNearestMultiple(average, 0.25));
        candidateScales.add(roundToNearestMultiple(1.0 / average, 0.25));
        double toIconSizeChangeFactor = average;
        for (double candidate : candidateScales) {
            if (candidate > 0.0 && candidate >= lowerBound && candidate <= upperBound) {
                toIconSizeChangeFactor = candidate;
                break;
            }
        }
        iconSizeChangeFactor = toIconSizeChangeFactor;
    }
    final double delegatePaintScale = iconSizeChangeFactor * toolkitScale;
    /* I experimented with allowing the delegate to handle all thisPaintScale <= toolkitScale
    cases, but this exposes the delegate to a wider range of inputs that may end up polluting
    its cache. Such bugs were observed to go away when
    com.sun.java.swing.plaf.windows.XPStyle.invalidateStyle was invoked by reflection. Better to
    just apply the workaround in those cases. Furthermore, we use rendering hints here that
    achieve a higher-quality scaling than that used by the delegate. */
    if (thisPaintScale == toolkitScale && iconSizeChangeFactor == 1.0) {
        // No workaround needed in this case; let the delegate do the painting.
        delegate.paintIcon(c, g0, x, y);
        return;
    }

    // Let the delegate paint the control in an off-screen buffer.
    Image img = createDelegatePaintedImage(c);
    // Now paint the buffer to the screen, scaled if necessary.
    Graphics2D g = (Graphics2D) g0.create();
    try {
        g.translate(x, y);
        if (thisPaintScale != 1.0) {
            /* Round translation to nearest device pixel, to avoid poor-quality interpolation.
            See similar code in ImageUtilities.ToolTipImage.paintIcon. */
            AffineTransform tx = g.getTransform();
            g.setTransform(new AffineTransform(thisPaintScale, 0, 0, thisPaintScale,
                    (int) tx.getTranslateX(),
                    (int) tx.getTranslateY()));
        }
        addScalingRenderingHints(g);
        g.scale(1.0 / delegatePaintScale, 1.0 / delegatePaintScale);
        // Final device pixel scaling is thisPaintScale / delegatePaintScale.
        g.drawImage(img, 0, 0, null);
    } finally {
        g.dispose();
    }
}
 
Example 17
Source Project: jdk8u60   File: CSSBorder.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void paintBorder(Component c, Graphics g,
                                    int x, int y, int width, int height) {
    if (!(g instanceof Graphics2D)) {
        return;
    }

    Graphics2D g2 = (Graphics2D) g.create();

    int[] widths = getWidths();

    // Position and size of the border interior.
    int intX = x + widths[LEFT];
    int intY = y + widths[TOP];
    int intWidth = width - (widths[RIGHT] + widths[LEFT]);
    int intHeight = height - (widths[TOP] + widths[BOTTOM]);

    // Coordinates of the interior corners, from NW clockwise.
    int[][] intCorners = {
        { intX, intY },
        { intX + intWidth, intY },
        { intX + intWidth, intY + intHeight },
        { intX, intY + intHeight, },
    };

    // Draw the borders for all sides.
    for (int i = 0; i < 4; i++) {
        Value style = getBorderStyle(i);
        Polygon shape = getBorderShape(i);
        if ((style != Value.NONE) && (shape != null)) {
            int sideLength = (i % 2 == 0 ? intWidth : intHeight);

            // "stretch" the border shape by the interior area dimension
            shape.xpoints[2] += sideLength;
            shape.xpoints[3] += sideLength;
            Color color = getBorderColor(i);
            BorderPainter painter = getBorderPainter(i);

            double angle = i * Math.PI / 2;
            g2.setClip(g.getClip()); // Restore initial clip
            g2.translate(intCorners[i][0], intCorners[i][1]);
            g2.rotate(angle);
            g2.clip(shape);
            painter.paint(shape, g2, color, i);
            g2.rotate(-angle);
            g2.translate(-intCorners[i][0], -intCorners[i][1]);
        }
    }
    g2.dispose();
}
 
Example 18
private void draw(Graphics2D g, int pixWidth, int pixHeight) {
	double sx = 0.0d;
	double sy = 0.0d;
	try {
		if (drawAxes) {
			sx = ((double) pixWidth - LABEL_MARGIN_Y)
					/ (xTransformation.transform(maxX) - xTransformation.transform(minX));
			sy = ((double) pixHeight - LABEL_MARGIN_X)
					/ (yTransformation.transform(maxY) - yTransformation.transform(minY));
		} else {
			sx = pixWidth / (xTransformation.transform(maxX) - xTransformation.transform(minX));
			sy = pixHeight / (yTransformation.transform(maxY) - yTransformation.transform(minY));
		}
	} catch (IllegalArgumentException e) {
		g.scale(1, -1);
		g.drawString("Cannot apply axis transformation. Please make sure that the value range", 0, -60);
		g.drawString("can be transformed by the selected axis transformation, for example", 0, -40);
		g.drawString("negative values or zero cannot be transformed by a log scale transformation", 0, -20);
		g.drawString("(applying a normalization operator to the desired range might help). ", 0, 0);
		return;
	}

	Graphics2D coordinateSpace = (Graphics2D) g.create();
	if (drawAxes) {
		coordinateSpace.translate(LABEL_MARGIN_Y, LABEL_MARGIN_X);
	}

	if (Double.isNaN(sx) || Double.isNaN(sy)) {
		coordinateSpace.scale(1, -1);
		coordinateSpace.drawString("No data points available (yet).", 0, -20);
		coordinateSpace.drawString("Zooming out with a right click might help.", 0, 0);
	} else {
		if (drawAxes) {
			transform.translate(LABEL_MARGIN_Y, LABEL_MARGIN_X);
		}
		transform.scale(sx, sy);
		transform.translate(-xTransformation.transform(minX), -yTransformation.transform(minY));

		drawGrid(coordinateSpace, -xTransformation.transform(minX), -yTransformation.transform(minY), sx, sy);
		drawPoints(coordinateSpace, -xTransformation.transform(minX), -yTransformation.transform(minY), sx, sy);
		drawToolTip(coordinateSpace, -xTransformation.transform(minX), -yTransformation.transform(minY), sx, sy);
	}
	coordinateSpace.dispose();
}
 
Example 19
public int print( Graphics graphics, PageFormat format, int index ) {
    Graphics2D g2d = (Graphics2D)graphics;
    g2d.translate(format.getImageableX(), format.getImageableY());
    doPaint(g2d);
    return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE;
}
 
Example 20
public void transformContextToDrawPrimitive(Graphics2D g) {
	
	g.translate(getWindowX(), getWindowY());

}