Why i can't see shadow generated with this ShadowRenderer? - java

I'm trying to use the ShadowRenderer from swingx to create a shadow for a panel. Here is what i did so far:
Creating the shadow renderer one time in the panel constructor.
public CustomPanel() {
super();
renderer = new ShadowRenderer(20, 0.5f, Color.RED);
}
Each time the panel is resized, i recalculate the new shadow.
#Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
shadow = renderer.createShadow(GraphicsUtilities.createCompatibleTranslucentImage(width, height));
}
And then i override the paintComponent method of my panel to draw the generated image:
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.drawImage(shadow, 0, 0, null);
//super.paintComponent(g);
}
But the shadow image is never shown. Why? I read this and i except my code to draw a kind of "shadowed" image generated by the shadow renderer.

Here's a shortened example of DropShadowDemo
JXPanel panel = new JXPanel() {
int shadowSize = 40;
ShadowRenderer renderer = new ShadowRenderer(shadowSize/ 2, 0.5f, Color.RED);
BufferedImage imageA =
XTestUtils.loadDefaultImage("moon.jpg");
BufferedImage shadow;
#Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
// not really needed here - the base image size is fixed
shadow = renderer.createShadow(imageA);
}
#Override
protected void paintComponent(Graphics g) {
int x = (getWidth() - imageA.getWidth()) / 2;
int y = (getHeight() - imageA.getHeight()) / 2;
Graphics2D g2 = (Graphics2D) g;
Composite c = g2.getComposite();
g2.setComposite(AlphaComposite.SrcOver.derive(renderer.getOpacity()));
g.drawImage(shadow, x - shadowSize / 2, y - shadowSize / 2, null);
g2.setComposite(c);
g.drawImage(imageA, x, y, null);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imageA.getWidth() + shadowSize, imageA.getHeight()+ shadowSize);
}
};
panel.setOpaque(false);

Related

Stable Line Custom Component

I used following code to create a custom component to draw edges of graphs, but the component has weird behaviors. sometimes it appear right, but sometimes it doesn't appear.
I looked other custom component samples but couldn't find where is the problem.
So the question is where is the problem?
public class EdgeLine extends JPanel
{
private static final long serialVersionUID = -5820537358240087280L;
public final Edge edge;
private int cHeight;
private int cWidth;
private Line2D line;
public EdgeLine(Edge edge)
{
Point firstLocation = edge.firstVertex.location;
Point secondLocation = edge.secondVertex.location;
this.edge = edge;
cWidth = Math.abs(firstLocation.y - secondLocation.y);
cHeight = Math.abs(firstLocation.x - secondLocation.x);
setSize(cHeight, cWidth);
this.setBackground(new Color(0, 0, 0, 0));
int xPoint = Math.min(firstLocation.x, secondLocation.x);
int yPoint = Math.min(firstLocation.y, secondLocation.y);
setLocation(new java.awt.Point(xPoint, yPoint));
line = new Line2D.Float(firstLocation.x - xPoint, firstLocation.y - yPoint
, secondLocation.x - xPoint, secondLocation.y - yPoint);
}
private void drawLine(Graphics2D graphic)
{
graphic = (Graphics2D) getGraphics();
graphic.setStroke(new BasicStroke(6));
graphic.setColor(Color.ORANGE);
graphic.draw(line);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (isOpaque())
{ //paint background
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
Graphics2D graphic = (Graphics2D) g.create();
drawLine(graphic);
graphic.dispose();
}
#Override
public Dimension getPreferredSize()
{
Dimension dim = new Dimension(cHeight, cWidth);
return dim;
}
}

Java changing colour of shape

i'm trying to make a rectangle in Java, done. I can also fill it in with solid colour, done. But I want to actually change the solid colour of the shape itself. I know with Graphics you can use g.setColor(); but I have had my component setup a special way as shown below:
public class Design extends JComponent {
private static final long serialVersionUID = 1L;
private List<Shape> shapesDraw = new ArrayList<Shape>();
private List<Shape> shapesFill = new ArrayList<Shape>();
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int screenWidth = gd.getDisplayMode().getWidth();
int screenHeight = gd.getDisplayMode().getHeight();
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for(Shape s : shapesDraw){
g2d.draw(s);
}
for(Shape s : shapesFill){
g2d.fill(s);
}
}
public void drawRect(int xPos, int yPos, int width, int height) {
shapesDraw.add(new Rectangle(xPos, yPos, width, height));
repaint();
}
public void fillRect(int xPos, int yPos, int width, int height) {
shapesFill.add(new Rectangle(xPos, yPos, width, height));
repaint();
}
public void drawTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) {
shapesDraw.add(new Polygon(
new int[]{leftX, topX, rightX},
new int[]{leftY, topY, rightY},
3));
repaint();
}
public void fillTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) {
shapesFill.add(new Polygon(
new int[]{leftX, topX, rightX},
new int[]{leftY, topY, rightY},
3));
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(screenWidth, screenHeight);
}
public int getWidth() {
return screenWidth;
}
public int getHeight() {
return screenHeight;
}
}
As you can see, instead of just drawing and filling, it uses a list to draw off of that. Is there a way I can change the colour inside the list< shape >? I preferably want the colour to be changeable inside each draw/fill shape.
Thanks for the help.
Updated from answer:
My class as follows from your ShapeWrapper example:
public class Design extends JComponent {
private static final long serialVersionUID = 1L;
private List<ShapeWrapper> shapesDraw = new ArrayList<ShapeWrapper>();
private List<ShapeWrapper> shapesFill = new ArrayList<ShapeWrapper>();
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int screenWidth = gd.getDisplayMode().getWidth();
int screenHeight = gd.getDisplayMode().getHeight();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for(ShapeWrapper s : shapesDraw){
g2d.setColor(s.color);
g2d.draw(s.shape);
}
for(ShapeWrapper s : shapesFill){
g2d.setColor(s.color);
g2d.fill(s.shape);
}
}
public void drawRect(int xPos, int yPos, int width, int height) {
shapesDraw.add(new Rectangle(xPos, yPos, width, height));
repaint();
}
public void fillRect(int xPos, int yPos, int width, int height) {
shapesFill.add(new Rectangle(xPos, yPos, width, height));
repaint();
}
public void drawTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) {
shapesDraw.add(new Polygon(
new int[]{leftX, topX, rightX},
new int[]{leftY, topY, rightY},
3));
repaint();
}
public void fillTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) {
shapesFill.add(new Polygon(
new int[]{leftX, topX, rightX},
new int[]{leftY, topY, rightY},
3));
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(getWidth(), getHeight());
}
public int getWidth() {
return screenWidth;
}
public int getHeight() {
return screenHeight;
}
}
class ShapeWrapper {
Color color;
Shape shape;
public ShapeWrapper(Color color , Shape shape){
this.color = color;
this.shape = shape;
}
}
Now I am coding in Eclipse and everything works fine except for ONE thing!!
Every time it says shapesDraw/shapesFill.add() it says:
The method add(ShapeWrapper) in the type List is not applicable for the arguments (Rectangle)
So close! Please respond.
You can use something like:
private class ShapeWrapper {
private Color color;
private Shape shape;
public ShapeWrapper(Color color , Shape shape){
this.color = color;
this.shape = shape;
}
}
instead of plain Shape for storing Shape+Color.
And paint them like next :
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for(ShapeWrapper s: shapesDraw){
g2d.setColor(s.color);
g2d.draw(s.shape);
}
for(ShapeWrappers s : shapesFill){
g2d.setColor(s.color);
g2d.fill(s.shape);
}
}
EDIT: according your exception, you try to add to typed list(ShapeWrapper) an object of another class(Shape), fix your methods like next :
public void drawRect(int xPos, int yPos, int width, int height) {
ShapeWrapper wr = new ShapeWrapper(Color.RED,new Rectangle(xPos, yPos, width, height));
shapesDraw.add(wr);
repaint();
}

Java: create shadow effect on image

I'm trying to create a shadow effect (with java) on an image.
I've seen multiple related questions and I've implemented several of the suggested solutions. Unfortunately I always have the same problem: the shadow effect repaints the entire image in gray (i.e. the shadow color) - hence the original image is not visible anymore.
Example of code I tested (based on the JIDE freely available library):
ShadowFactory sf = new ShadowFactory(2, 0.5f, Color.black);
ImageIO.write(sf.createShadow(ImageIO.read(new File("c:\\out2.png"))), "png", new File("c:\\out3.png"));
No need to says that I tested this with multiple source files (out2.png).
I'm clueless: any hint/help would be highly appreciated.
The over all theory is simple. Basically, you need to generate a mask of the image (using a AlphaComposite and fill that resulting image with the color you want (also using an AlphaComposite. This, of course, all works on the alpha channel of the image...
Once you have that mask, you need to combine the two images (overlaying the original image with the masked image)
This examples make use of JHLabs filters to supply the blur...
public class TestImageDropShadow {
public static void main(String[] args) {
new TestImageDropShadow();
}
public TestImageDropShadow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage background;
public ImagePane() {
try {
BufferedImage master = ImageIO.read(getClass().getResource("/Scaled.png"));
background = applyShadow(master, 5, Color.BLACK, 0.5f);
} catch (IOException ex) {
Logger.getLogger(TestImageDropShadow.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
public static void applyQualityRenderingHints(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
public static BufferedImage createCompatibleImage(int width, int height) {
return createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
public static BufferedImage createCompatibleImage(int width, int height, int transparency) {
BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
public static BufferedImage createCompatibleImage(BufferedImage image) {
return createCompatibleImage(image, image.getWidth(), image.getHeight());
}
public static BufferedImage createCompatibleImage(BufferedImage image,
int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency());
}
public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage generateMask(BufferedImage imgSource, Color color, float alpha) {
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
return imgBlur;
}
public static BufferedImage generateBlur(BufferedImage imgSource, int size, Color color, float alpha) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
public static BufferedImage applyShadow(BufferedImage imgSource, int size, Color color, float alpha) {
BufferedImage result = createCompatibleImage(imgSource, imgSource.getWidth() + (size * 2), imgSource.getHeight() + (size * 2));
Graphics2D g2d = result.createGraphics();
g2d.drawImage(generateShadow(imgSource, size, color, alpha), size, size, null);
g2d.drawImage(imgSource, 0, 0, null);
g2d.dispose();
return result;
}
public static BufferedImage generateShadow(BufferedImage imgSource, int size, Color color, float alpha) {
int imgWidth = imgSource.getWidth() + (size * 2);
int imgHeight = imgSource.getHeight() + (size * 2);
BufferedImage imgMask = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgMask.createGraphics();
applyQualityRenderingHints(g2);
int x = Math.round((imgWidth - imgSource.getWidth()) / 2f);
int y = Math.round((imgHeight - imgSource.getHeight()) / 2f);
g2.drawImage(imgSource, x, y, null);
g2.dispose();
// ---- Blur here ---
BufferedImage imgGlow = generateBlur(imgMask, (size * 2), color, alpha);
return imgGlow;
}
public static Image applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth(null);
int height = maskImage.getHeight(null);
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth(null)) / 2;
int y = (height - sourceImage.getHeight(null)) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
}
This is my Version:
private static Image dropShadow(BufferedImage img) {
// a filter which converts all colors except 0 to black
ImageProducer prod = new FilteredImageSource(img.getSource(), new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
if (rgb == 0)
return 0;
else
return 0xff000000;
}
});
// create whe black image
Image shadow = Toolkit.getDefaultToolkit().createImage(prod);
// result
BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
Graphics2D g = (Graphics2D) result.getGraphics();
// draw shadow with offset
g.drawImage(shadow, 10, 0, null);
// draw original image
g.drawImage(img, 0, 0, null);
return result;
}

How to draw a Round rectangle in java with normal rectangle outline

For my java application i need a Round rectangle with an outline that looks like a normal rectangle, like this
I know you can do that by drawing a normal rectangle and a RoundRect inside it but i don't want to draw a RoundRect inside it because I want to draw something else in it.
So a round rect with normal corners. How do I draw that in Java?
The problem is that the rectangle looks like this if I use layers:
The corners are filled up with the wrong color. How do I prevent that?
I can think of two approaches. The first is to generate a Shape that represents the square outter edge and the rounded inner edge.
The second would be to use a AlphaComposite to generate a masked result.
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MaskedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MaskedPane extends JPanel {
public MaskedPane() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage outter = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = outter.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
BufferedImage inner = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = inner.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRoundRect(10, 10, getWidth() - 20, getHeight() - 20, 20, 20);
g2d.dispose();
BufferedImage masked = applyMask(outter, inner, AlphaComposite.DST_OUT);
g.drawImage(masked, 0, 0, this);
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth();
int height = maskImage.getHeight();
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth()) / 2;
int y = (height - sourceImage.getHeight()) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return (BufferedImage) applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
}
}
Updated with Shape example
Finally had time to bang one out...
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ShapedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShapedPane extends JPanel {
public ShapedPane() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(new RounedFrame(getWidth(), getHeight(), 10, 20));
g2d.dispose();
}
}
public class RounedFrame extends Path2D.Float {
public RounedFrame(float width, float height, float thickness, float radius) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height);
lineTo(0, height);
lineTo(0, 0);
float innerWidth = width - thickness;
float innerHeight = height - thickness;
moveTo(thickness + radius, thickness);
lineTo(innerWidth - radius, thickness);
curveTo(innerWidth, thickness, innerWidth, thickness, innerWidth, thickness + radius);
lineTo(innerWidth, innerHeight - radius);
curveTo(innerWidth, innerHeight, innerWidth, innerHeight, innerWidth - radius, innerHeight);
lineTo(thickness + radius, innerHeight);
curveTo(thickness, innerHeight, thickness, innerHeight, thickness, innerHeight - radius);
lineTo(thickness, thickness + radius);
curveTo(thickness, thickness, thickness, thickness, thickness + radius, thickness);
closePath();
setWindingRule(WIND_EVEN_ODD);
}
}
}
Updated
From a comment by Andrew, you could simplify the use of the shape example by using Area
You could replace the paintComponent from the above example with this one...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Area area = new Area(new Rectangle(0, 0, getWidth(), getHeight()));
area.subtract(new Area(new RoundRectangle2D.Float(10, 10, getWidth() - 20, getHeight() - 20, 20, 20)));
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(area);
g2d.dispose();
}
Which is much simpler :D
Something like:
paintComponent(Graphics g) {
//If you want more: Graphics2D g2 = (Graphics2D) g;
Rect rect = getBounds();
g.setColor(Color.BLACK);
g.fillRect(rect.x, rect,y, rect.width, rect.height);
rect.grow(-4, -4);
g.setColor(getBackground());
g.fillRoundRect(rect.x, rect,y, rect.width, rect.height, 5, 5);
}
E.G.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class CustomBorderWithContent {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
int w = 200;
int h = 100;
int pad = 4;
BufferedImage img = new BufferedImage(
w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Ripped/adapted from Joop's answer
g.setColor(Color.BLACK);
g.fillRect(0, 0, w, h);
g.setColor(Color.ORANGE);
g.fillRoundRect(pad, pad, w-2*pad, h-2*pad, 25, 25);
// Now..
g.setColor(Color.BLUE);
g.drawString("Something else..", 20, 25);
g.dispose();
JOptionPane.showMessageDialog(
null, new JLabel(new ImageIcon(img)));
}
};
SwingUtilities.invokeLater(r);
}
}

Graphics2D draw image inside of defined quadrilateral

I cannot find a draw image overload inside of Graphics2D which will enable me to perform such a task, can someone help me figure out how one might do this - preferably without swapping to more advanced graphics frameworks such as OpenGl,
thanks.
To clarify, a quad can be defined by anything with four-sides; that means a diamond or a rectangle or more elaborate shapes.
Mre has removed many of his remarks and so It seems as though I am responding to no-one, however all I have said in the comments were responses to what mre had said.
See Andrew Thomson's solution for the basics.
Instead of using a "text shape", I created a Shape using:
Polygon polygon = new Polygon();
polygon.addPoint(250, 50);
polygon.addPoint(350, 50);
polygon.addPoint(450, 150);
polygon.addPoint(350, 150);
g.setClip(polygon);
g.drawImage(originalImage, 0, 0, null);
Inherited Graphicsimage drawing methods
drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
drawImage(Image img, int x, int y, ImageObserver observer)
drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
Choose your poison. Since you weren't even able to locate these, I'm assuming that going into detail about Intermediate Images when faced with scaling and frequent rendering would be futile.
Example 1 -- drawing a circle in a square
public class DrawCircleInSquare {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
// Clear background to white
g2.setColor(Color.WHITE);
g2.clearRect(0, 0, getWidth(), getHeight());
// Draw square
g2.setColor(Color.BLACK);
g2.drawRect(50, 50, 100, 100);
// Draw circle inside square
g2.setColor(Color.RED);
g2.fillOval(88, 88, 24, 24);
g2.dispose();
}
#Override
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
};
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Output
Example 2 -- draw an image in a square
public class DrawImageInSquare {
private static BufferedImage bi;
public static void main(String[] args){
try {
// Load image
loadImage();
// Create and show GUI
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
// handle exception
}
}
private static void loadImage() throws IOException{
bi = ImageIO.read(new File("src/resources/psyduck.png"));
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
// Clear background to white
g2.setColor(Color.WHITE);
g2.clearRect(0, 0, getWidth(), getHeight());
// Draw square
g2.setColor(Color.BLACK);
g2.drawRect(50, 50, 100, 100);
// Draw image inside square
g2.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(bi, 50, 50, 100, 100, null);
g2.dispose();
}
#Override
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
};
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Output

Categories

Resources