diff options
-rw-r--r-- | .gitignore (renamed from apcs/.gitignore) | 0 | ||||
-rw-r--r-- | apcs/RoundedRectangleTest.java | 62 | ||||
-rw-r--r-- | apcs/SongPlayer.java | 2 | ||||
-rw-r--r-- | apcs/shadowtest.java | 26 | ||||
-rw-r--r-- | dropShadow/GraphicsUtilities.java | 555 | ||||
-rw-r--r-- | dropShadow/Main.form | 96 | ||||
-rw-r--r-- | dropShadow/Main.java | 125 | ||||
-rw-r--r-- | dropShadow/PanelShadow.java | 100 | ||||
-rw-r--r-- | dropShadow/ShadowRenderer.java | 185 | ||||
-rw-r--r-- | dropShadow/ShadowType.java | 5 |
10 files changed, 1139 insertions, 17 deletions
diff --git a/apcs/.gitignore b/.gitignore index 6b468b6..6b468b6 100644 --- a/apcs/.gitignore +++ b/.gitignore diff --git a/apcs/RoundedRectangleTest.java b/apcs/RoundedRectangleTest.java index e506ec4..c24772c 100644 --- a/apcs/RoundedRectangleTest.java +++ b/apcs/RoundedRectangleTest.java @@ -3,6 +3,7 @@ package apcs; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; +import java.awt.geom.RoundRectangle2D; import javax.swing.*; @@ -15,42 +16,56 @@ public class RoundedRectangleTest extends JFrame { setVisible(true); } public void paint(Graphics g) { + //DropShadowBorder shadow = new DropShadowBorder(); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(Color.DARK_GRAY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - /* + g2d.fillRoundRect(10, 50, 150, 150, 30, 30); // to draw a rounded rectangle. + + /*Graphics2D g2d = (Graphics2D) g; Color holdColor = g2d.getColor(); g2d.setColor(Color.black); AffineTransform holdTransform = g2d.getTransform(); // want the shadow to be one line width pixel offset - float lineWidth = g2d.getStroke() instanceof BasicStroke ? ((BasicStroke) (g2d.getStroke())).getLineWidth() - : 1.0f; + float lineWidth; + if (g2d.getStroke() instanceof BasicStroke) + { + lineWidth = ((BasicStroke) (g2d.getStroke())).getLineWidth(); + } + else + { + lineWidth = 1.0f; + } //System.err.println("DrawingUtilities.drawShadowedShape(): lineWidth = "+lineWidth); - g2d.translate(lineWidth, lineWidth); - g2d.fillRoundRect(10, 50, 150, 150, 50, 50); // to draw a rounded rectangle. - g2d.setColor(holdColor); - g2d.setTransform(holdTransform); + //g2d.translate(lineWidth, lineWidth); + g2d.fillRoundRect(10, 50, 150, 150, 30, 30); + //g2d.setColor(holdColor); + //g2d.setTransform(holdTransform); + //g2d.drawRoundRect(10, 50, 150, 150, 30, 30); */ - g2d.fillRoundRect(10, 50, 150, 150, 50, 50); // to draw a rounded rectangle. - + + } public static void main(String []args) { new RoundedRectangleTest(); } - - /*/from www . j av a2 s .c o m - * @param shape the shape to be drawn - * @param g2d the drawing context - */ + public static void drawShadowedShape(Shape shape, Graphics2D g2d) { Color holdColor = g2d.getColor(); g2d.setColor(Color.black); AffineTransform holdTransform = g2d.getTransform(); // want the shadow to be one line width pixel offset - float lineWidth = g2d.getStroke() instanceof BasicStroke ? ((BasicStroke) (g2d.getStroke())).getLineWidth() - : 1.0f; + float lineWidth; + if (g2d.getStroke() instanceof BasicStroke) + { + lineWidth = ((BasicStroke) (g2d.getStroke())).getLineWidth(); + } + else + { + lineWidth = 1.0f; + } //System.err.println("DrawingUtilities.drawShadowedShape(): lineWidth = "+lineWidth); g2d.translate(lineWidth, lineWidth); g2d.draw(shape); @@ -58,4 +73,19 @@ public class RoundedRectangleTest extends JFrame { g2d.setTransform(holdTransform); g2d.draw(shape); } + + public static void drawShadowedShape2(Shape shape, Graphics2D g2d) { + Color holdColor = g2d.getColor(); + g2d.setColor(Color.black); + AffineTransform holdTransform = g2d.getTransform(); + // want the shadow to be one line width pixel offset + float lineWidth = g2d.getStroke() instanceof BasicStroke ? ((BasicStroke) (g2d.getStroke())).getLineWidth() + : 1.0f; + //System.err.println("DrawingUtilities.drawShadowedShape(): lineWidth = "+lineWidth); + g2d.translate(lineWidth, lineWidth); + g2d.draw(shape); + g2d.setColor(holdColor); + g2d.setTransform(holdTransform); + g2d.draw(shape); + } }
\ No newline at end of file diff --git a/apcs/SongPlayer.java b/apcs/SongPlayer.java index 50e06aa..686bc7c 100644 --- a/apcs/SongPlayer.java +++ b/apcs/SongPlayer.java @@ -4,7 +4,7 @@ *Teacher: *Description: */ -package cs; +package apcs; import java.awt.*; import java.awt.event.*; diff --git a/apcs/shadowtest.java b/apcs/shadowtest.java new file mode 100644 index 0000000..b6acba5 --- /dev/null +++ b/apcs/shadowtest.java @@ -0,0 +1,26 @@ +package apcs; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics2D; + +import java.awt.Shape; + +import java.awt.geom.AffineTransform; + +public class shadowtest { + public static void drawShadowedShape(Shape shape, Graphics2D g2d) { + Color holdColor = g2d.getColor(); + g2d.setColor(Color.black); + AffineTransform holdTransform = g2d.getTransform(); + // want the shadow to be one line width pixel offset + float lineWidth = g2d.getStroke() instanceof BasicStroke ? ((BasicStroke) (g2d.getStroke())).getLineWidth() + : 1.0f; + //System.err.println("DrawingUtilities.drawShadowedShape(): lineWidth = "+lineWidth); + g2d.translate(lineWidth, lineWidth); + g2d.draw(shape); + g2d.setColor(holdColor); + g2d.setTransform(holdTransform); + g2d.draw(shape); + } +}
\ No newline at end of file diff --git a/dropShadow/GraphicsUtilities.java b/dropShadow/GraphicsUtilities.java new file mode 100644 index 0000000..832e59b --- /dev/null +++ b/dropShadow/GraphicsUtilities.java @@ -0,0 +1,555 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package dropShadow; + +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.awt.GraphicsConfiguration; +import java.awt.Transparency; +import java.awt.Graphics; +import java.awt.GraphicsEnvironment; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.io.IOException; +import java.net.URL; +import javax.imageio.ImageIO; + +/** + * <p> + * <code>GraphicsUtilities</code> contains a set of tools to perform common + * graphics operations easily. These operations are divided into several themes, + * listed below.</p> + * <h2>Compatible Images</h2> + * <p> + * Compatible images can, and should, be used to increase drawing performance. + * This class provides a number of methods to load compatible images directly + * from files or to convert existing images to compatibles images.</p> + * <h2>Creating Thumbnails</h2> + * <p> + * This class provides a number of methods to easily scale down images. Some of + * these methods offer a trade-off between speed and result quality and shouuld + * be used all the time. They also offer the advantage of producing compatible + * images, thus automatically resulting into better runtime performance.</p> + * <p> + * All these methodes are both faster than + * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce + * better-looking results than the various <code>drawImage()</code> methods in + * {@link java.awt.Graphics}, which can be used for image scaling.</p> + * <h2>Image Manipulation</h2> + * <p> + * This class provides two methods to get and set pixels in a buffered image. + * These methods try to avoid unmanaging the image in order to keep good + * performance.</p> + * + * @author Romain Guy <romain.guy@mac.com> + */ +public class GraphicsUtilities { + + private GraphicsUtilities() { + } + + // Returns the graphics configuration for the primary screen + private static GraphicsConfiguration getGraphicsConfiguration() { + return GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(); + } + + /** + * <p> + * Returns a new <code>BufferedImage</code> using the same color model as + * the image passed as a parameter. The returned image is only compatible + * with the image passed as a parameter. This does not mean the returned + * image is compatible with the hardware.</p> + * + * @param image the reference image from which the color model of the new + * image is obtained + * @return a new <code>BufferedImage</code>, compatible with the color model + * of <code>image</code> + */ + public static BufferedImage createColorModelCompatibleImage(BufferedImage image) { + ColorModel cm = image.getColorModel(); + return new BufferedImage(cm, + cm.createCompatibleWritableRaster(image.getWidth(), + image.getHeight()), + cm.isAlphaPremultiplied(), null); + } + + /** + * <p> + * Returns a new compatible image with the same width, height and + * transparency as the image specified as a parameter.</p> + * + * @see java.awt.Transparency + * @see #createCompatibleImage(int, int) + * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) + * @see #createCompatibleTranslucentImage(int, int) + * @see #loadCompatibleImage(java.net.URL) + * @see #toCompatibleImage(java.awt.image.BufferedImage) + * @param image the reference image from which the dimension and the + * transparency of the new image are obtained + * @return a new compatible <code>BufferedImage</code> with the same + * dimension and transparency as <code>image</code> + */ + public static BufferedImage createCompatibleImage(BufferedImage image) { + return createCompatibleImage(image, image.getWidth(), image.getHeight()); + } + + /** + * <p> + * Returns a new compatible image of the specified width and height, and the + * same transparency setting as the image specified as a parameter.</p> + * + * @see java.awt.Transparency + * @see #createCompatibleImage(java.awt.image.BufferedImage) + * @see #createCompatibleImage(int, int) + * @see #createCompatibleTranslucentImage(int, int) + * @see #loadCompatibleImage(java.net.URL) + * @see #toCompatibleImage(java.awt.image.BufferedImage) + * @param width the width of the new image + * @param height the height of the new image + * @param image the reference image from which the transparency of the new + * image is obtained + * @return a new compatible <code>BufferedImage</code> with the same + * transparency as <code>image</code> and the specified dimension + */ + public static BufferedImage createCompatibleImage(BufferedImage image, + int width, int height) { + return getGraphicsConfiguration().createCompatibleImage(width, height, + image.getTransparency()); + } + + /** + * <p> + * Returns a new opaque compatible image of the specified width and + * height.</p> + * + * @see #createCompatibleImage(java.awt.image.BufferedImage) + * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) + * @see #createCompatibleTranslucentImage(int, int) + * @see #loadCompatibleImage(java.net.URL) + * @see #toCompatibleImage(java.awt.image.BufferedImage) + * @param width the width of the new image + * @param height the height of the new image + * @return a new opaque compatible <code>BufferedImage</code> of the + * specified width and height + */ + public static BufferedImage createCompatibleImage(int width, int height) { + return getGraphicsConfiguration().createCompatibleImage(width, height); + } + + /** + * <p> + * Returns a new translucent compatible image of the specified width and + * height.</p> + * + * @see #createCompatibleImage(java.awt.image.BufferedImage) + * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) + * @see #createCompatibleImage(int, int) + * @see #loadCompatibleImage(java.net.URL) + * @see #toCompatibleImage(java.awt.image.BufferedImage) + * @param width the width of the new image + * @param height the height of the new image + * @return a new translucent compatible <code>BufferedImage</code> of the + * specified width and height + */ + public static BufferedImage createCompatibleTranslucentImage(int width, + int height) { + return getGraphicsConfiguration().createCompatibleImage(width, height, + Transparency.TRANSLUCENT); + } + + /** + * <p> + * Returns a new compatible image from a URL. The image is loaded from the + * specified location and then turned, if necessary into a compatible + * image.</p> + * + * @see #createCompatibleImage(java.awt.image.BufferedImage) + * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) + * @see #createCompatibleImage(int, int) + * @see #createCompatibleTranslucentImage(int, int) + * @see #toCompatibleImage(java.awt.image.BufferedImage) + * @param resource the URL of the picture to load as a compatible image + * @return a new translucent compatible <code>BufferedImage</code> of the + * specified width and height + * @throws java.io.IOException if the image cannot be read or loaded + */ + public static BufferedImage loadCompatibleImage(URL resource) + throws IOException { + BufferedImage image = ImageIO.read(resource); + return toCompatibleImage(image); + } + + /** + * <p> + * Return a new compatible image that contains a copy of the specified + * image. This method ensures an image is compatible with the hardware, and + * therefore optimized for fast blitting operations.</p> + * + * @see #createCompatibleImage(java.awt.image.BufferedImage) + * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) + * @see #createCompatibleImage(int, int) + * @see #createCompatibleTranslucentImage(int, int) + * @see #loadCompatibleImage(java.net.URL) + * @param image the image to copy into a new compatible image + * @return a new compatible copy, with the same width and height and + * transparency and content, of <code>image</code> + */ + public static BufferedImage toCompatibleImage(BufferedImage image) { + if (image.getColorModel().equals( + getGraphicsConfiguration().getColorModel())) { + return image; + } + + BufferedImage compatibleImage + = getGraphicsConfiguration().createCompatibleImage( + image.getWidth(), image.getHeight(), + image.getTransparency()); + Graphics g = compatibleImage.getGraphics(); + g.drawImage(image, 0, 0, null); + g.dispose(); + + return compatibleImage; + } + + /** + * <p> + * Returns a thumbnail of a source image. <code>newSize</code> defines the + * length of the longest dimension of the thumbnail. The other dimension is + * then computed according to the dimensions ratio of the original + * picture.</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, int) + * @see #createThumbnail(java.awt.image.BufferedImage, int) + * @see #createThumbnail(java.awt.image.BufferedImage, int, int) + * @param image the source image + * @param newSize the length of the largest dimension of the thumbnail + * @return a new compatible <code>BufferedImage</code> containing a + * thumbnail of <code>image</code> + * @throws IllegalArgumentException if <code>newSize</code> is larger than + * the largest dimension of <code>image</code> or <= 0 + */ + public static BufferedImage createThumbnailFast(BufferedImage image, + int newSize) { + float ratio; + int width = image.getWidth(); + int height = image.getHeight(); + + if (width > height) { + if (newSize >= width) { + throw new IllegalArgumentException("newSize must be lower than" + + " the image width"); + } else if (newSize <= 0) { + throw new IllegalArgumentException("newSize must" + + " be greater than 0"); + } + + ratio = (float) width / (float) height; + width = newSize; + height = (int) (newSize / ratio); + } else { + if (newSize >= height) { + throw new IllegalArgumentException("newSize must be lower than" + + " the image height"); + } else if (newSize <= 0) { + throw new IllegalArgumentException("newSize must" + + " be greater than 0"); + } + + ratio = (float) height / (float) width; + height = newSize; + width = (int) (newSize / ratio); + } + + BufferedImage temp = createCompatibleImage(image, width, height); + 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; + } + + /** + * <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 + * <= 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; + } + + /** + * <p> + * Returns a thumbnail of a source image. <code>newSize</code> defines the + * length of the longest dimension of the thumbnail. The other dimension is + * then computed according to the dimensions ratio of the original + * picture.</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, int) + * @see #createThumbnailFast(java.awt.image.BufferedImage, int) + * @see #createThumbnail(java.awt.image.BufferedImage, int, int) + * @param image the source image + * @param newSize the length of the largest dimension of the thumbnail + * @return a new compatible <code>BufferedImage</code> containing a + * thumbnail of <code>image</code> + * @throws IllegalArgumentException if <code>newSize</code> is larger than + * the largest dimension of <code>image</code> or <= 0 + */ + public static BufferedImage createThumbnail(BufferedImage image, + int newSize) { + int width = image.getWidth(); + int height = image.getHeight(); + + boolean isWidthGreater = width > height; + + if (isWidthGreater) { + if (newSize >= width) { + throw new IllegalArgumentException("newSize must be lower than" + + " the image width"); + } + } else if (newSize >= height) { + throw new IllegalArgumentException("newSize must be lower than" + + " the image height"); + } + + if (newSize <= 0) { + throw new IllegalArgumentException("newSize must" + + " be greater than 0"); + } + + float ratioWH = (float) width / (float) height; + float ratioHW = (float) height / (float) width; + + BufferedImage thumb = image; + + do { + if (isWidthGreater) { + width /= 2; + if (width < newSize) { + width = newSize; + } + height = (int) (width / ratioWH); + } else { + height /= 2; + if (height < newSize) { + height = newSize; + } + width = (int) (height / ratioHW); + } + + 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 (newSize != (isWidthGreater ? width : height)); + + return thumb; + } + + /** + * <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 > 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; + } + + /** + * <p> + * Returns an array of pixels, stored as integers, from a + * <code>BufferedImage</code>. The pixels are grabbed from a rectangular + * area defined by a location and two dimensions. Calling this method on an + * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and + * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p> + * + * @param img the source image + * @param x the x location at which to start grabbing pixels + * @param y the y location at which to start grabbing pixels + * @param w the width of the rectangle of pixels to grab + * @param h the height of the rectangle of pixels to grab + * @param pixels a pre-allocated array of pixels of size w*h; can be null + * @return <code>pixels</code> if non-null, a new array of integers + * otherwise + * @throws IllegalArgumentException is <code>pixels</code> is non-null and + * of length < w*h + */ + public static int[] getPixels(BufferedImage img, + int x, int y, int w, int h, int[] pixels) { + if (w == 0 || h == 0) { + return new int[0]; + } + + if (pixels == null) { + pixels = new int[w * h]; + } else if (pixels.length < w * h) { + throw new IllegalArgumentException("pixels array must have a length" + + " >= w*h"); + } + + int imageType = img.getType(); + if (imageType == BufferedImage.TYPE_INT_ARGB + || imageType == BufferedImage.TYPE_INT_RGB) { + Raster raster = img.getRaster(); + return (int[]) raster.getDataElements(x, y, w, h, pixels); + } + + // Unmanages the image + return img.getRGB(x, y, w, h, pixels, 0, w); + } + + /** + * <p> + * Writes a rectangular area of pixels in the destination + * <code>BufferedImage</code>. Calling this method on an image of type + * different from <code>BufferedImage.TYPE_INT_ARGB</code> and + * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p> + * + * @param img the destination image + * @param x the x location at which to start storing pixels + * @param y the y location at which to start storing pixels + * @param w the width of the rectangle of pixels to store + * @param h the height of the rectangle of pixels to store + * @param pixels an array of pixels, stored as integers + * @throws IllegalArgumentException is <code>pixels</code> is non-null and + * of length < w*h + */ + public static void setPixels(BufferedImage img, + int x, int y, int w, int h, int[] pixels) { + if (pixels == null || w == 0 || h == 0) { + return; + } else if (pixels.length < w * h) { + throw new IllegalArgumentException("pixels array must have a length" + + " >= w*h"); + } + + int imageType = img.getType(); + if (imageType == BufferedImage.TYPE_INT_ARGB + || imageType == BufferedImage.TYPE_INT_RGB) { + WritableRaster raster = img.getRaster(); + raster.setDataElements(x, y, w, h, pixels); + } else { + // Unmanages the image + img.setRGB(x, y, w, h, pixels, 0, w); + } + } +} diff --git a/dropShadow/Main.form b/dropShadow/Main.form new file mode 100644 index 0000000..f894d2a --- /dev/null +++ b/dropShadow/Main.form @@ -0,0 +1,96 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + <SyntheticProperty name="generateCenter" type="boolean" value="true"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + </AuxValues> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="0" attributes="0"> + <Component id="jPanel1" max="32767" attributes="0"/> + <EmptySpace min="-2" pref="0" max="-2" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <Component id="jPanel1" alignment="0" max="32767" attributes="0"/> + </Group> + </DimensionLayout> + </Layout> + <SubComponents> + <Container class="javax.swing.JPanel" name="jPanel1"> + <Properties> + <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor"> + <Color blue="ff" green="ff" red="ff" type="rgb"/> + </Property> + </Properties> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="0" attributes="0"> + <EmptySpace min="-2" pref="93" max="-2" attributes="0"/> + <Component id="panelShadow1" min="-2" max="-2" attributes="0"/> + <EmptySpace pref="166" max="32767" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="0" attributes="0"> + <EmptySpace min="-2" pref="54" max="-2" attributes="0"/> + <Component id="panelShadow1" min="-2" max="-2" attributes="0"/> + <EmptySpace pref="81" max="32767" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + </Layout> + <SubComponents> + <Container class="main.PanelShadow" name="panelShadow1"> + <Properties> + <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor"> + <Color blue="d2" green="4e" red="5c" type="rgb"/> + </Property> + <Property name="shadowColor" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor"> + <Color blue="4f" green="4f" red="4f" type="rgb"/> + </Property> + <Property name="shadowType" type="main.ShadowType" editor="org.netbeans.modules.form.editors.EnumEditor"> + <Value id="BOT_RIGHT"/> + </Property> + </Properties> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <EmptySpace min="0" pref="500" max="32767" attributes="0"/> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <EmptySpace min="0" pref="500" max="32767" attributes="0"/> + </Group> + </DimensionLayout> + </Layout> + </Container> + </SubComponents> + </Container> + </SubComponents> +</Form> diff --git a/dropShadow/Main.java b/dropShadow/Main.java new file mode 100644 index 0000000..943656f --- /dev/null +++ b/dropShadow/Main.java @@ -0,0 +1,125 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package dropShadow; + +/** + * + * @author RAVEN + */ +public class Main extends javax.swing.JFrame { + + /** + * Creates new form Main + */ + public Main() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + PanelShadow panelShadow1 = new PanelShadow(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jPanel1.setBackground(new java.awt.Color(255, 255, 255)); + + panelShadow1.setBackground(new java.awt.Color(92, 78, 210)); + panelShadow1.setShadowColor(new java.awt.Color(79, 79, 79)); + panelShadow1.setShadowType(ShadowType.BOT_RIGHT); + + javax.swing.GroupLayout panelShadow1Layout = new javax.swing.GroupLayout(panelShadow1); + panelShadow1.setLayout(panelShadow1Layout); + panelShadow1Layout.setHorizontalGroup( + panelShadow1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 500, Short.MAX_VALUE) + ); + panelShadow1Layout.setVerticalGroup( + panelShadow1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 500, Short.MAX_VALUE) + ); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(93, 93, 93) + .addComponent(panelShadow1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(166, Short.MAX_VALUE)) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(54, 54, 54) + .addComponent(panelShadow1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(81, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(0, 0, 0)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + + pack(); + setLocationRelativeTo(null); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + //</editor-fold> + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new Main().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel jPanel1; + private PanelShadow panelShadow1; + // End of variables declaration//GEN-END:variables +} diff --git a/dropShadow/PanelShadow.java b/dropShadow/PanelShadow.java new file mode 100644 index 0000000..be1c2f3 --- /dev/null +++ b/dropShadow/PanelShadow.java @@ -0,0 +1,100 @@ +package dropShadow; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import javax.swing.JPanel; + +public class PanelShadow extends JPanel { + + public ShadowType getShadowType() { + return shadowType; + } + + public void setShadowType(ShadowType shadowType) { + this.shadowType = shadowType; + } + + public int getShadowSize() { + return shadowSize; + } + + public void setShadowSize(int shadowSize) { + this.shadowSize = shadowSize; + } + + public float getShadowOpacity() { + return shadowOpacity; + } + + public void setShadowOpacity(float shadowOpacity) { + this.shadowOpacity = shadowOpacity; + } + + public Color getShadowColor() { + return shadowColor; + } + + public void setShadowColor(Color shadowColor) { + this.shadowColor = shadowColor; + } + + private ShadowType shadowType = ShadowType.CENTER; + private int shadowSize = 6; + private float shadowOpacity = 0.5f; + private Color shadowColor = Color.BLACK; + + public PanelShadow() { + setOpaque(false); + } + + @Override + protected void paintComponent(Graphics grphcs) { + createShadow(grphcs); + super.paintComponent(grphcs); + } + + private void createShadow(Graphics grphcs) { + Graphics2D g2 = (Graphics2D) grphcs; + int size = shadowSize * 2; + int x = 0; + int y = 0; + int width = getWidth() - size; + int height = getHeight() - size; + if (shadowType == ShadowType.TOP) { + x = shadowSize; + y = size; + } else if (shadowType == ShadowType.BOT) { + x = shadowSize; + y = 0; + } else if (shadowType == ShadowType.TOP_LEFT) { + x = size; + y = size; + } else if (shadowType == ShadowType.TOP_RIGHT) { + x = 0; + y = size; + } else if (shadowType == ShadowType.BOT_LEFT) { + x = size; + y = 0; + } else if (shadowType == ShadowType.BOT_RIGHT) { + x = 0; + y = 0; + } else { + // Center + x = shadowSize; + y = shadowSize; + } + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = img.createGraphics(); + g.setColor(getBackground()); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + // g.fillRoundRect(0, 0, width, height, 10, 10); + g.fillOval(0, 0, width, width); + // Create Shadow + ShadowRenderer render = new ShadowRenderer(shadowSize, shadowOpacity, shadowColor); + g2.drawImage(render.createShadow(img), 0, 0, null); + g2.drawImage(img, x, y, null); + } +} diff --git a/dropShadow/ShadowRenderer.java b/dropShadow/ShadowRenderer.java new file mode 100644 index 0000000..d80d2c8 --- /dev/null +++ b/dropShadow/ShadowRenderer.java @@ -0,0 +1,185 @@ +package dropShadow; + +import java.awt.Color; +import java.awt.image.BufferedImage; + +public class ShadowRenderer { + + // size of the shadow in pixels (defines the fuzziness) + private int size = 5; + + // opacity of the shadow + private float opacity = 0.5f; + + // color of the shadow + private Color color = Color.BLACK; + + public ShadowRenderer() { + this(5, 0.5f, Color.BLACK); + } + + public ShadowRenderer(final int size, final float opacity, final Color color) { + this.size = size; + this.opacity = opacity; + this.color = color; + } + + public Color getColor() { + return color; + } + + public float getOpacity() { + return opacity; + } + + public int getSize() { + return size; + } + + public BufferedImage createShadow(final BufferedImage image) { + // Written by Sesbastien Petrucci + int shadowSize = size * 2; + + int srcWidth = image.getWidth(); + int srcHeight = image.getHeight(); + + int dstWidth = srcWidth + shadowSize; + int dstHeight = srcHeight + shadowSize; + + int left = size; + int right = shadowSize - left; + + int yStop = dstHeight - right; + + int shadowRgb = color.getRGB() & 0x00FFFFFF; + int[] aHistory = new int[shadowSize]; + int historyIdx; + + int aSum; + + BufferedImage dst = new BufferedImage(dstWidth, dstHeight, + BufferedImage.TYPE_INT_ARGB); + + int[] dstBuffer = new int[dstWidth * dstHeight]; + int[] srcBuffer = new int[srcWidth * srcHeight]; + + GraphicsUtilities.getPixels(image, 0, 0, srcWidth, srcHeight, srcBuffer); + + int lastPixelOffset = right * dstWidth; + float hSumDivider = 1.0f / shadowSize; + float vSumDivider = opacity / shadowSize; + + int[] hSumLookup = new int[256 * shadowSize]; + for (int i = 0; i < hSumLookup.length; i++) { + hSumLookup[i] = (int) (i * hSumDivider); + } + + int[] vSumLookup = new int[256 * shadowSize]; + for (int i = 0; i < vSumLookup.length; i++) { + vSumLookup[i] = (int) (i * vSumDivider); + } + + int srcOffset; + + // horizontal pass : extract the alpha mask from the source picture and + // blur it into the destination picture + for (int srcY = 0, dstOffset = left * dstWidth; srcY < srcHeight; srcY++) { + + // first pixels are empty + for (historyIdx = 0; historyIdx < shadowSize;) { + aHistory[historyIdx++] = 0; + } + + aSum = 0; + historyIdx = 0; + srcOffset = srcY * srcWidth; + + // compute the blur average with pixels from the source image + for (int srcX = 0; srcX < srcWidth; srcX++) { + + int a = hSumLookup[aSum]; + dstBuffer[dstOffset++] = a << 24; // store the alpha value only + // the shadow color will be added in the next pass + + aSum -= aHistory[historyIdx]; // substract the oldest pixel from the sum + + // extract the new pixel ... + a = srcBuffer[srcOffset + srcX] >>> 24; + aHistory[historyIdx] = a; // ... and store its value into history + aSum += a; // ... and add its value to the sum + + if (++historyIdx >= shadowSize) { + historyIdx -= shadowSize; + } + } + + // blur the end of the row - no new pixels to grab + for (int i = 0; i < shadowSize; i++) { + + int a = hSumLookup[aSum]; + dstBuffer[dstOffset++] = a << 24; + + // substract the oldest pixel from the sum ... and nothing new to add ! + aSum -= aHistory[historyIdx]; + + if (++historyIdx >= shadowSize) { + historyIdx -= shadowSize; + } + } + } + + // vertical pass + for (int x = 0, bufferOffset = 0; x < dstWidth; x++, bufferOffset = x) { + + aSum = 0; + + // first pixels are empty + for (historyIdx = 0; historyIdx < left;) { + aHistory[historyIdx++] = 0; + } + + // and then they come from the dstBuffer + for (int y = 0; y < right; y++, bufferOffset += dstWidth) { + int a = dstBuffer[bufferOffset] >>> 24; // extract alpha + aHistory[historyIdx++] = a; // store into history + aSum += a; // and add to sum + } + + bufferOffset = x; + historyIdx = 0; + + // compute the blur avera`ge with pixels from the previous pass + for (int y = 0; y < yStop; y++, bufferOffset += dstWidth) { + + int a = vSumLookup[aSum]; + dstBuffer[bufferOffset] = a << 24 | shadowRgb; // store alpha value + shadow color + + aSum -= aHistory[historyIdx]; // substract the oldest pixel from the sum + + a = dstBuffer[bufferOffset + lastPixelOffset] >>> 24; // extract the new pixel ... + aHistory[historyIdx] = a; // ... and store its value into history + aSum += a; // ... and add its value to the sum + + if (++historyIdx >= shadowSize) { + historyIdx -= shadowSize; + } + } + + // blur the end of the column - no pixels to grab anymore + for (int y = yStop; y < dstHeight; y++, bufferOffset += dstWidth) { + + int a = vSumLookup[aSum]; + dstBuffer[bufferOffset] = a << 24 | shadowRgb; + + aSum -= aHistory[historyIdx]; // substract the oldest pixel from the sum + + if (++historyIdx >= shadowSize) { + historyIdx -= shadowSize; + } + } + } + + GraphicsUtilities.setPixels(dst, 0, 0, dstWidth, dstHeight, dstBuffer); + return dst; + } +} diff --git a/dropShadow/ShadowType.java b/dropShadow/ShadowType.java new file mode 100644 index 0000000..8cdcb76 --- /dev/null +++ b/dropShadow/ShadowType.java @@ -0,0 +1,5 @@ +package dropShadow; + +public enum ShadowType { + CENTER, TOP_RIGHT, TOP_LEFT, BOT_RIGHT, BOT_LEFT, BOT, TOP +} |