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

The following examples show how to use java.awt.Graphics2D#setRenderingHint() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ZoomSliderPanel.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    if(shapes == null) initShapes();
    // Keep shapes centered on panel.
    double x = (getWidth()  - scale*size.width)/2;
    double y = (getHeight() - scale*size.height)/2;
    AffineTransform at = AffineTransform.getTranslateInstance(x, y);
    at.scale(scale, scale);
    g2.setPaint(Color.blue);
    g2.draw(at.createTransformedShape(shapes[0]));
    g2.setPaint(Color.green.darker());
    g2.draw(at.createTransformedShape(shapes[1]));
    g2.setPaint(new Color(240,240,200));
    g2.fill(at.createTransformedShape(shapes[2]));
    g2.setPaint(Color.red);
    g2.draw(at.createTransformedShape(shapes[2]));
}
 
Example 2
Source File: FastScatterPlot.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Draws the gridlines for the plot, if they are visible.
 *
 * @param g2  the graphics device.
 * @param dataArea  the data area.
 * @param ticks  the ticks.
 */
protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea,
        List ticks) {

    if (!isRangeGridlinesVisible()) {
        return;
    }
    Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, 
            RenderingHints.VALUE_STROKE_NORMALIZE);

    Iterator iterator = ticks.iterator();
    while (iterator.hasNext()) {
        ValueTick tick = (ValueTick) iterator.next();
        double v = this.rangeAxis.valueToJava2D(tick.getValue(),
                dataArea, RectangleEdge.LEFT);
        Line2D line = new Line2D.Double(dataArea.getMinX(), v,
                dataArea.getMaxX(), v);
        g2.setPaint(getRangeGridlinePaint());
        g2.setStroke(getRangeGridlineStroke());
        g2.draw(line);
    }
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);
}
 
Example 3
Source File: ImageManufacture.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static BufferedImage scaleImage(BufferedImage source, int width,
        int height) {
    if (width == source.getWidth() && height == source.getHeight()) {
        return source;
    }
    if (width <= 0 || height <= 0) {
        return source;
    }
    int imageType = source.getType();
    if (imageType == BufferedImage.TYPE_CUSTOM) {
        imageType = BufferedImage.TYPE_INT_ARGB;
    }
    BufferedImage target = new BufferedImage(width, height, imageType);
    Graphics2D g = target.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setBackground(CommonFxValues.TRANSPARENT);
    g.drawImage(source, 0, 0, width, height, null);
    g.dispose();
    return target;
}
 
Example 4
Source File: ShapeView.java    From lgmodeler with GNU General Public License v3.0 6 votes vote down vote up
public void paint(Graphics g){
	Graphics2D g2d = (Graphics2D)g;
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	if(selected){
		g2d.setColor(Resources.SELECT_COLOR);
	} else {
		g2d.setColor(fillColor);
	}
	g2d.fillRoundRect(2, 2, getWidth()-4, getHeight()-4, 12, 12);
	g2d.setColor(outlineColor);
	g2d.setStroke(outlineStroke);
	g2d.drawRoundRect(2, 2, getWidth()-4, getHeight()-4, 12, 12);
	g2d.drawImage(icon, 8, 0, null);
	g2d.drawImage(Resources.VISIBLE_ICONS[shape.enabled()?0:1], 40, 0, null);
	g2d.drawImage(Resources.LOCK_ICONS[shape.locked()?1:0], 70, 0, null);
	g2d.drawImage(Resources.DELETE_ICON, getWidth() - 32, 0, null);
}
 
Example 5
Source File: AbstractThrobber.java    From magarena with GNU General Public License v3.0 6 votes vote down vote up
private BufferedImage getNextFrameImage(final int angle) {

        final int W = getWidth();
        final int H = getHeight();
        if (W <= 0 || H <= 0) {
            return null;
        }

        final BufferedImage image = ImageHelper.getCompatibleBufferedImage(W, H, Transparency.TRANSLUCENT);
        final Graphics2D g2d = image.createGraphics();

        if (isAntiAliasOn) {
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // These make a visible difference producing smoother looking images...
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        }

        drawFrame(g2d, angle);

        return image;

    }
 
Example 6
Source File: TSFrame.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void render(Graphics g, int w, int h, boolean useNonOpaque) {
    if (useNonOpaque) {
        Graphics2D g2d = (Graphics2D)g;
        GradientPaint p =
            new GradientPaint(0.0f, 0.0f,
                              new Color(rnd.nextInt(0xffffff)),
                              w, h,
                              new Color(rnd.nextInt(0xff),
                                        rnd.nextInt(0xff),
                                        rnd.nextInt(0xff), 0),
                              true);
        g2d.setPaint(p);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(0, 0, w, h);
    } else {
        g.setColor(new Color(rnd.nextInt(0xffffff)));
        g.fillRect(0, 0, w, h);
    }
}
 
Example 7
Source File: IncorrectAlphaConversionBicubic.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) {
    final GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
    final GraphicsDevice gd = ge.getDefaultScreenDevice();
    final GraphicsConfiguration gc = gd.getDefaultConfiguration();
    final VolatileImage vi =
            gc.createCompatibleVolatileImage(SIZE, SIZE, TRANSLUCENT);
    final BufferedImage bi = makeUnmanagedBI(gc, TRANSLUCENT);
    final int expected = bi.getRGB(2, 2);

    int attempt = 0;
    BufferedImage snapshot;
    while (true) {
        if (++attempt > 10) {
            throw new RuntimeException("Too many attempts: " + attempt);
        }
        vi.validate(gc);
        final Graphics2D g2d = vi.createGraphics();
        g2d.setComposite(AlphaComposite.Src);
        g2d.scale(2, 2);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                             RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(bi, 0, 0, null);
        g2d.dispose();

        snapshot = vi.getSnapshot();
        if (vi.contentsLost()) {
            continue;
        }
        break;
    }
    final int actual = snapshot.getRGB(2, 2);
    if (actual != expected) {
        System.err.println("Actual: " + Integer.toHexString(actual));
        System.err.println("Expected: " + Integer.toHexString(expected));
        throw new RuntimeException("Test failed");
    }
}
 
Example 8
Source File: TestTransform.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void testFontOfSize(float sz, Object textHint) {
    BufferedImage bi = new BufferedImage(200, 200,
                               BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setFont(g2.getFont().deriveFont(sz));
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textHint);
    g2.drawString("test", 100, 100);
}
 
Example 9
Source File: ColorScalePanel.java    From chipster with MIT License 5 votes vote down vote up
@Override
public void paintIcon(Component component, Graphics g, int x, int y) {
	super.paintIcon(component, g, x, y);
	Graphics2D g2 = (Graphics2D)g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);

	DataPoint.paintBall(2, 2, 18, 18, color, g2);
}
 
Example 10
Source File: Renderer.java    From gpx-animator with Apache License 2.0 5 votes vote down vote up
private Graphics2D getGraphics(final BufferedImage bi) {
    final Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    return g2;
}
 
Example 11
Source File: RotaryController.java    From jsyn with Apache License 2.0 5 votes vote down vote up
/**
 * Override this method if you want to draw your own knob.
 *
 * @param g graphics context
 * @param x position of center of knob
 * @param y position of center of knob
 * @param radius of knob in pixels
 * @param angle in radians. Zero is straight up.
 */
public void drawKnob(Graphics g, int x, int y, int radius, double angle) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int diameter = radius * 2;
    // Draw shaded side.
    g.setColor(knobColor.darker());
    g.fillOval(x - radius + 2, y - radius + 2, diameter, diameter);
    g.setColor(knobColor);
    g.fillOval(x - radius, y - radius, diameter, diameter);

    // Draw line or other indicator of knob position.
    drawIndicator(g, x, y, radius, angle);
}
 
Example 12
Source File: ImageTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void initContext(TestEnvironment env, GraphicsTests.Context ctx) {
    super.initContext(env, ctx);
    ImageTests.Context ictx = (ImageTests.Context) ctx;

    ictx.src = env.getSrcImage();
    ictx.touchSrc = env.isEnabled(doTouchSrc);
    if (hasGraphics2D) {
        Graphics2D g2d = (Graphics2D) ctx.graphics;
        final Object modifier = env.getModifier(interpolation);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, modifier);
    }
}
 
Example 13
Source File: StrokeBorder.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Paints the border for the specified component
 * with the specified position and size.
 * If the border was not specified with a {@link Paint} object,
 * the component's foreground color will be used to render the border.
 * If the component's foreground color is not available,
 * the default color of the {@link Graphics} object will be used.
 *
 * @param c       the component for which this border is being painted
 * @param g       the paint graphics
 * @param x       the x position of the painted border
 * @param y       the y position of the painted border
 * @param width   the width of the painted border
 * @param height  the height of the painted border
 *
 * @throws NullPointerException if the specified {@code g} is {@code null}
 */
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    float size = this.stroke.getLineWidth();
    if (size > 0.0f) {
        g = g.create();
        if (g instanceof Graphics2D) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(this.stroke);
            g2d.setPaint(this.paint != null ? this.paint : c == null ? null : c.getForeground());
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                 RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.draw(new Rectangle2D.Float(x + size / 2, y + size / 2, width - size, height - size));
        }
        g.dispose();
    }
}
 
Example 14
Source File: SystemMonitor.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void paintComponent(Graphics g) {
	super.paintComponent(g);

	GeneralPath path = new GeneralPath();

	Dimension d = getSize();
	int monitorWidth = (int) d.getWidth() - 2 * MARGIN;
	int monitorHeight = (int) d.getHeight() - 2 * MARGIN;

	long total = Runtime.getRuntime().totalMemory();

	Graphics2D g2d = (Graphics2D) g;
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

	if (this.font == null) {
		this.font = g2d.getFont().deriveFont(12f);
	}

	g2d.setColor(Colors.WHITE);
	g2d.fillRect(MARGIN, MARGIN, monitorWidth, monitorHeight);

	path.moveTo(MARGIN, MARGIN + monitorHeight);
	for (int i = 0; i < memory.length; i++) {
		int index = (currentMeasurement + i) % memory.length;
		path.lineTo(MARGIN + i * monitorWidth / (memory.length - 1),
				MARGIN + monitorHeight - monitorHeight * memory[index] / total);
	}
	path.lineTo(MARGIN + monitorWidth, MARGIN + monitorHeight);
	path.closePath();

	g2d.setColor(gridColor);
	for (int x = 0; x < GRID_X + 1; x++) {
		g2d.drawLine(MARGIN + x * monitorWidth / GRID_X, MARGIN, MARGIN + x * monitorWidth / GRID_X,
				MARGIN + monitorHeight);
	}
	for (int y = 0; y < GRID_Y + 1; y++) {
		g2d.drawLine(MARGIN, MARGIN + y * monitorHeight / GRID_Y, MARGIN + monitorWidth,
				MARGIN + y * monitorHeight / GRID_Y);
	}

	Color currentMemoryColor = memoryColor;
	if (currentlyUsed > 0.2d * Runtime.getRuntime().maxMemory()) {
		double more = currentlyUsed - 0.2d * Runtime.getRuntime().maxMemory();
		double factor = more / (0.6d * Runtime.getRuntime().maxMemory());
		currentMemoryColor = getMemoryColor(Math.max(Math.min(1.0d, factor), 0.0d));
	}
	g2d.setColor(currentMemoryColor);
	g2d.fill(path);
	g2d.setColor(lineColor);
	g2d.draw(path);

	// text
	String maxString = Tools.formatSizeInBytes(total) + " used. Will use up to "
			+ Tools.formatSizeInBytes(Runtime.getRuntime().maxMemory());
	int totalHeight = 2 * font.getSize() + 2 * MARGIN;
	// MARGIN;
	if (totalHeight < getHeight()) {
		g2d.setFont(font);
		g2d.setColor(textColor);
		g2d.drawString(maxString, 2 * MARGIN, monitorHeight - font.getSize() + MARGIN);
	}
}
 
Example 15
Source File: SegmentedButtonPainter.java    From seaglass with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
    SegmentType segmentStatus = getSegmentType(c);
    int         newHeight     = getButtonHeight(c, height);

    int yOffset = (height - newHeight) / 2;

    height = newHeight;

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

    int x = focusInsets.left;
    int y = focusInsets.top + yOffset;

    width  -= focusInsets.left + focusInsets.right;
    height -= focusInsets.top + focusInsets.bottom;

    boolean useToolBarFocus = isInToolBar(c);
    Shape   s;

    if (focused) {
        s = createOuterFocus(segmentStatus, x, y, width, height);
        g.setPaint(getFocusPaint(s, FocusType.OUTER_FOCUS, useToolBarFocus));
        g.draw(s);
        s = createInnerFocus(segmentStatus, x, y, width, height);
        g.setPaint(getFocusPaint(s, FocusType.INNER_FOCUS, useToolBarFocus));
        g.draw(s);
    }

    if (!isInToolBar(c) || this instanceof TexturedButtonPainter) {
        s = createBorder(segmentStatus, x, y, width, height);

        if (!focused) {
            dropShadow.fill(g, s);
        }

        g.setPaint(getCommonBorderPaint(s, type));
        g.fill(s);

        s = createInterior(segmentStatus, x, y, width, height);
        g.setPaint(getCommonInteriorPaint(s, type));
        g.fill(s);
    }
}
 
Example 16
Source File: GraphicsUtilities.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * <p>Returns a thumbnail of a source image.</p>
 * <p>This method favors speed over quality. When the new size is less than
 * half the longest dimension of the source image,
 * {@link #createThumbnail(BufferedImage, int)} or
 * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
 * to ensure the quality of the result without sacrificing too much
 * performance.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
 * @param image the source image
 * @param newWidth the width of the thumbnail
 * @param newHeight the height of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newWidth</code> is larger than
 *   the width of <code>image</code> or if code>newHeight</code> is larger
 *   than the height of <code>image</code> or if one of the dimensions
 *   is &lt;= 0
 */
public static BufferedImage createThumbnailFast(BufferedImage image,
                                                int newWidth, int newHeight) {
    if (newWidth >= image.getWidth() ||
        newHeight >= image.getHeight()) {
        throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                           " be greater than the image" +
                                           " dimensions");
    } else if (newWidth <= 0 || newHeight <= 0) {
        throw new IllegalArgumentException("newWidth and newHeight must" +
                                           " be greater than 0");
    }

    BufferedImage temp = createCompatibleImage(image, newWidth, newHeight);
    Graphics2D g2 = temp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
    g2.dispose();

    return temp;
}
 
Example 17
Source File: FlatUIUtils.java    From FlatLaf with Apache License 2.0 4 votes vote down vote up
/**
 * Sets rendering hints used for painting.
 */
public static void setRenderingHints( Graphics2D g ) {
	g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
	g.setRenderingHint( RenderingHints.KEY_STROKE_CONTROL,
		MAC_USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE );
}
 
Example 18
Source File: FrameImage.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * combineBufferedImage.
 * SCIPIO: 2017-07-10: modified to take a typeReferenceImage instance of bufImgType, so we have the full
 * information to replicate the original image type, needed for indexed images.
 */
public static BufferedImage combineBufferedImage(Image image1, Image image2, BufferedImage typeReferenceImage) {
    // Full image loading
    image1 = new ImageIcon(image1).getImage();
    image2 = new ImageIcon(image2).getImage();

    // New BufferedImage creation
    // SCIPIO: indexed images fix
    BufferedImage bufferedImage;
    Graphics2D g;
    if (image1 instanceof BufferedImage && ImagePixelType.isTypeImageOpFriendly(((BufferedImage) image1).getType())) {
        // still create a copy to avoid modifying the original
        bufferedImage = ImageTransform.cloneBufferedImage((BufferedImage) image1);
        g = bufferedImage.createGraphics();
    } else {
        bufferedImage = ImageTransform.createBufferedImage(ImageType.DEFAULT_IMAGEOP.getImageTypeInfoFor(typeReferenceImage), image1.getWidth(null),
                image1.getHeight(null));
        g = bufferedImage.createGraphics();
        g.drawImage(image1, null, null);
    }

    // Draw Image combine
    Point2D center = new Point2D.Float(bufferedImage.getHeight() / 2f, bufferedImage.getWidth() / 2f);
    AffineTransform at = AffineTransform.getTranslateInstance(center.getX( ) - (image2.getWidth(null) / 2f), center.getY( ) - (image2.getHeight(null) / 2f));
    g.transform(at);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(image2, 0, 0, null);
    Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .35f);
    g.setComposite(c);
    at = AffineTransform.getTranslateInstance(center.getX( ) - (bufferedImage.getWidth(null) / 2f), center.getY( ) - (bufferedImage.getHeight(null) / 2f));
    g.setTransform(at);
    g.drawImage(bufferedImage, 0, 0, null);
    g.dispose();

    // SCIPIO: new: we convert to the target type only at the very end, in separate step, so the previous operations don't suffer from color loss
    if (ImageType.imageMatchesRequestedType(bufferedImage, typeReferenceImage)) {
        return bufferedImage;
    } else {
        BufferedImage resultImage = ImageTransform.createCompatibleBufferedImage(typeReferenceImage, bufferedImage.getWidth(null), bufferedImage.getHeight(null));
        ImageTransform.copyToBufferedImage(bufferedImage, resultImage);
        return( resultImage );
    }
}
 
Example 19
Source File: LightBulb.java    From mars-sim with 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 20
Source File: GraphicsUtilities.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * <p>Returns a thumbnail of a source image.</p>
 * <p>This method offers a good trade-off between speed and quality.
 * The result looks better than
 * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
 * the new size is less than half the longest dimension of the source
 * image, yet the rendering speed is almost similar.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @param image the source image
 * @param newWidth the width of the thumbnail
 * @param newHeight the height of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newWidth</code> is larger than
 *   the width of <code>image</code> or if code>newHeight</code> is larger
 *   than the height of <code>image or if one the dimensions is not &gt; 0</code>
 */
public static BufferedImage createThumbnail(BufferedImage image,
                                            int newWidth, int newHeight) {
    int width = image.getWidth();
    int height = image.getHeight();

    if (newWidth >= width || newHeight >= height) {
        throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                           " be greater than the image" +
                                           " dimensions");
    } else if (newWidth <= 0 || newHeight <= 0) {
        throw new IllegalArgumentException("newWidth and newHeight must" +
                                           " be greater than 0");
    }

    BufferedImage thumb = image;

    do {
        if (width > newWidth) {
            width /= 2;
            if (width < newWidth) {
                width = newWidth;
            }
        }

        if (height > newHeight) {
            height /= 2;
            if (height < newHeight) {
                height = newHeight;
            }
        }

        BufferedImage temp = createCompatibleImage(image, width, height);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
        g2.dispose();

        thumb = temp;
    } while (width != newWidth || height != newHeight);

    return thumb;
}