Here you can find the source of paintWithWatermarkHelper(JComponent component, ImageIcon watermark, Graphics g)
Parameter | Description |
---|---|
g | a parameter |
public static void paintWithWatermarkHelper(JComponent component, ImageIcon watermark, Graphics g)
//package com.java2s; import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Composite; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JViewport; public class Main { /**/* w ww . j a v a 2 s .com*/ * A helper function to paint a watermark for a component. * This should be called in the paintComponent method before calling the super class method. * @param g */ public static void paintWithWatermarkHelper(JComponent component, ImageIcon watermark, Graphics g) { Graphics2D g2 = (Graphics2D) g; Paint oldPaint = g2.getPaint(); g2.setPaint(component.getBackground()); try { // Fill in the background of the component. g2.fillRect(0, 0, component.getWidth(), component.getHeight()); // Draw the background image, if any. if (watermark != null) { // draw the image centred in the visible area, and scaled to fit Rectangle viewRect = new Rectangle(0, 0, component.getWidth(), component.getHeight()); Component parent = component.getParent(); if (parent instanceof JViewport) { JViewport viewport = (JViewport) parent; viewRect = viewport.getViewRect(); } int imageWidth = watermark.getIconWidth(); int imageHeight = watermark.getIconHeight(); double xZoom = viewRect.getWidth() / imageWidth; double yZoom = viewRect.getHeight() / imageHeight; double zoom = Math.min(xZoom, yZoom); int drawnWidth = (int) (imageWidth * zoom); int drawnHeight = (int) (imageHeight * zoom); int x = viewRect.x + (viewRect.width - drawnWidth) / 2; int y = viewRect.y + (viewRect.height - drawnHeight) / 2; Composite oldComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25f)); g2.drawImage(watermark.getImage(), x, y, x + drawnWidth, y + drawnHeight, 0, 0, imageWidth, imageHeight, null); g2.setComposite(oldComposite); } } finally { g2.setPaint(oldPaint); } } /** * Returns the parent component of the component c that has the given type, * or <code>null</code> if such parent does not exist. * @param c * @param type * @return Component */ public static Component getParent(Component c, Class<? extends Container> type) { c = c.getParent(); while (c != null) { // assume that they are loaded by the same classloader if (c.getClass() == type) { return c; } c = c.getParent(); } return null; } }