How to delete shapes drawn on an Image - java

I am developing a small Paint tool. And I am able to load and draw Lines or Circles and other shapes on an image. Also I have an eraser tool to erase the shapes that I have drawn.
This is code for that:
g.setColor(getColor().WHITE);
g.fillRect(getXAxis() - getThickness(), getYAxis() - getThickness(), getThickness() * 2, getThickness() * 2);
My problem is that, If I have loaded an image and drawn some shapes on it. Then when I tried to erase the shapes, the image is also gets replaced with white color.
Is there any way to set the image as the background while using fillRect() to erase the shape, so that my image will be untouched.

Here is the example. To test it you need to replace my image with your background image.
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
* <code>PaintTryout</code>.
*
* #author smedvynskyy
*/
public class PaintPanel extends JPanel {
private Image backgroundImage;
private BufferedImage paintImage;
public PaintPanel() {
try {
// replace this image with your image
backgroundImage = ImageIO.read(new File("E:\\icons\\blackboard.png"));
paintImage = new BufferedImage(backgroundImage.getWidth(this),
backgroundImage.getHeight(this), BufferedImage.TYPE_INT_ARGB);
} catch (final Exception e) {
e.printStackTrace();
}
}
public void fillRect() {
final Graphics g = paintImage.createGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, 50, 50);
g.dispose();
repaint();
}
public void clearRect() {
final Graphics2D g = paintImage.createGraphics();
g.setColor(new Color(0, 0, 0, 0));
g.setComposite(AlphaComposite.Clear); // overpaint
g.fillRect(0, 0, 50, 50);
g.dispose();
repaint();
}
/**
* {#inheritDoc}
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, this);
g.drawImage(paintImage, 0, 0, this);
}
/**
* {#inheritDoc}
*/
#Override
public Dimension getPreferredSize() {
return new Dimension(backgroundImage.getWidth(this),
backgroundImage.getHeight(this));
}
public static void main(String[] args) {
final JFrame frm = new JFrame("Tesp paint");
final PaintPanel p = new PaintPanel();
frm.add(p);
final JPanel buttons = new JPanel();
final JButton fill = new JButton("Fill Rect");
fill.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
p.fillRect();
}
});
final JButton clear = new JButton("Clear Rect");
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
p.clearRect();
}
});
buttons.add(fill);
buttons.add(clear);
frm.add(buttons, BorderLayout.SOUTH);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}

The easy way to do this is to draw the lines in XOR mode. Then, to erase them, you just draw them again.

Related

JButton image rendering badly

I'm making a application with Swing, and I want to add to the main panel a button with a cross icon on it. But when I draw an image on it, the image is rendering weirdly.
I've already tried several things like resizing the image outside the application, and the cross is made with IllustratorCC so I don't think it's the quality of the source image that's the issue.
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class ImageRenderingBadly extends JPanel
{
BufferedImage cross;
public ImageRenderingBadly()
{
try {
URL url = new URL("https://i.imgur.com/cWGntek.png");
cross = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(cross,0,0,null);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(new Dimension(200,200));
frame.setBackground(new Color(0));
ImageRenderingBadly panel = new ImageRenderingBadly();
frame.setContentPane(panel);
frame.setVisible(true);
}
}
Source:
Rendering badly:
FOUND THE SOLUTION
Use antialiasing in paintComponent :(https://docs.oracle.com/javase/tutorial/2d/advanced/quality.html)
#Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(rh);
g2.drawImage(cross,0,0,null);
}
It works for me:
Note that I have used the image to create two images and Icons, one for the button, and one for the depressed state, to indicate that it has been pressed.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class XButtonTest {
private static final String X_IMG_PATH = "https://i.imgur.com/cWGntek.png";
public static void main(String[] args) {
try {
URL xImgUrl = new URL(X_IMG_PATH);
BufferedImage xImage = ImageIO.read(xImgUrl);
int w = xImage.getWidth();
int h = xImage.getHeight();
BufferedImage pressedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = pressedImg.createGraphics();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, w, h);
g2.drawImage(xImage, 0, 0, null);
g2.dispose();
Icon icon = new ImageIcon(xImage);
Icon pressedIcon = new ImageIcon(pressedImg);
JButton button = new JButton(icon);
button.setPressedIcon(pressedIcon);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
JPanel panel = new JPanel();
panel.add(button);
JOptionPane.showMessageDialog(null, panel, "Test", JOptionPane.PLAIN_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I figured out that the "drawImage" render badly image and that' the problem I think :
public class Panel extends JPanel
{
BufferedImage image;
public Panel() {
super();
try {
image = ImageIO.read(new File("images/BMW-TA.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
Source : https://i.imgur.com/ebr17CV.jpg
Rendering : https://i.imgur.com/Z01I7mn.png
FOUND THE SOLUTION
Use antialiasing in paintComponent :
#Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(rh);
g2.drawImage(cross,0,0,null);
}

Displaying an image over another

Currently I am having an issue whereby the Robot.png is replacing the image of my gameboard.png . I want to make it so that the robot .png is ontop of the board and be able to move the robot around the board.
Board.Java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Board extends JPanel {
private Image gameboard;
public Board(){
initBoard();
}
private void initBoard(){
loadImage();
int w = gameboard.getWidth(this);
int h = gameboard.getHeight(this);
setPreferredSize(new Dimension(w,h));
}
private void loadImage(){
ImageIcon i = new ImageIcon("res/gameboard.png");
gameboard = i.getImage();
}
#Override
public void paintComponent(Graphics g){
g.drawImage(gameboard,0,0,null);
}
}
Player.Java
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player extends JPanel {
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
ImageIcon ic = new ImageIcon("res/Robot.png");
Image image1 = ic.getImage();
g2d.drawImage(image1, 100, 100, null);
}
}
GameGUI.Java
import javax.swing.JFrame;
public class GameGui extends JFrame {
public GameGui(){
initGui();
}
public void initGui(){
add(new Board());
add(new Player());
setTitle("11+ Game");
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(1240,620);
}
}
You don't need to reload the robot image every time. You should use ImageIO to load it, and save it in a member variable.
Otherwise, the way to not have the image overwrite the whole background image is to use height and width parameters with your drawImage call
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
ImageIcon ic = new ImageIcon("res/Robot.png");
Image image1 = ic.getImage();
int width = ..., height = ...;
g2d.drawImage(image1, 100, 100, width, height, null);
}

How to make a translucent JPanel within the region Jpanel

I want to make a translucent JPanel for which I can choose the x-coordinate, y-coordinate, width and height. I have found some material that made a translucent JPanel that filled its parent container, but I don't need this effect. I need a translucent JPanel whose position can be specified in the parent container, such that only this area is translucent, while others in the parent container are opaque. I tried this code but it is incorrect. The resultant area is smaller than the area I intend. What is wrong, or how I can get this effect?
public class TranslucentJPanel extends JPanel {
private float transparency;
public TranslucentJPanel(){
}
/**set the transparency
*
* #param transparency:the transparency you want to set
*
* #return void
*/
public void setTransparent(float transparency) {
this.transparency = transparency;
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D graphics2d = (Graphics2D) g.create();
graphics2d.setComposite(AlphaComposite.SrcOver.derive(transparency));
graphics2d.fill(getBounds());
graphics2d.dispose();
}
}
So, two things come to mind immediately...
First, don't use getBounds, the Grapghics context is already translated to the components x/y position, so you're doubling that up. Instead, simply use 0x0 and provide the width and height, something like...
graphics2d.fillRect(0, 0, getWidth(), getHeight());
Also, remember, most Swing components are opaque by default, this includes the JList, JScrollPane and it's JViewport, you need to set these to be transparent if you want them to be see through at all.
Also, the "default" renderer that the JList uses also renderers it self as opaque, so you need to be able to supply your own if you want the items to be transparent...
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("Bananas");
model.addElement("Apples");
model.addElement("Pears");
model.addElement("Grapes");
model.addElement("Tim Tams");
JList list = new JList(model);
list.setCellRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setOpaque(isSelected);
return this;
}
});
list.setOpaque(false);
JScrollPane sp = new JScrollPane(list);
sp.setOpaque(false);
sp.getViewport().setOpaque(false);
TranslucentPane tp = new TranslucentPane();
tp.setLayout(new GridBagLayout());
tp.setLayout(new BorderLayout());
tp.add(sp);
JFrame frame = new JFrame("Testing");
frame.setContentPane(new BackgroundPane());
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TranslucentPane extends JPanel {
private float alpha = 0.75f;
public TranslucentPane() {
setOpaque(false);
setBorder(new EmptyBorder(5, 5, 5, 5));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
public class BackgroundPane extends JPanel {
private BufferedImage background;
public BackgroundPane() {
try {
background = ImageIO.read(new File("C:\\Users\\shane\\Dropbox\\MegaTokyo\\thumnails\\megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}

How to 'undraw' an Image?

I am trying to make a simple game in Java, All i need to do is draw an im onto the screen and then wait for 5 seconds then 'undraw it'.
Code (this class draws the image on the screen):
package com.mainwindow.draw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class MainWindow extends JPanel{
Image Menu;
String LogoSource = "Logo.png";
public MainWindow() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
Menu = ii.getImage();
Timer timer = new Timer(5, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);
}
}
Code #2 (this creates the JFrame)
package com.mainwindow.draw;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Frame extends JFrame {
public Frame() {
add(new MainWindow());
setTitle("Game Inviroment Graphics Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
new Frame();
}
}
Use some kind of flag to determine if the image should be drawn or not and simply change it's state as needed...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (draw) {
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);
}
}
Then change the state of the flag when you need to...
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
draw = false;
repaint();
}
});
Note: It's not recommended to to override paint, paint is at the top of the paint change and can easily break how the paint process works, causing no end of issues. Instead, it's normally recommended to use paintComponent instead. See Performing Custom Painting for more details
Also note: javax.swing.Timer expects the delay in milliseconds...5 is kind of fast...

How to use AffineTransform.quadrantRotate to rotate a bitmap?

I want to rotate a bitmap about its center point, and then draw it into a larger graphics context.
The bitmap is 40x40 pixels. The graphics context is 500x500 pixels. This is what I'm doing:
BufferedImage bi = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
AffineTransform at = new AffineTransform();
at.quadrantRotate(1, -20, -20); // rotate 90 degrees around center point.
at.translate(100, 40); // I want to put its top-left corner at 100,40.
g.drawImage(smallerBitmap, at, null);
...
I'm probably using quadrantRotate() incorrectly - if I remove that line, my image gets drawn at position 100,40 correctly at least.
What am I doing wrong?
Thanks
The order of your transformation matters. Basically your example code is saying "rotate the image by 90 degrees AND then translate it...."
So, using your code (rotate, then translate) produces...
Switching the order (translate then rotate) produces
...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestRotation100 {
public static void main(String[] args) {
new TestRotation100();
}
public TestRotation100() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
final TestPane testPane = new TestPane();
final JSlider slider = new JSlider(0, 3);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
testPane.setQuad(slider.getValue());
}
});
slider.setValue(0);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.add(slider, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
private int quad = 0;
public TestPane() {
try {
img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Rampage_Small.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void setQuad(int quad) {
this.quad = quad;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = new AffineTransform();
at.translate(100, 40);
at.quadrantRotate(quad, img.getWidth() / 2, img.getHeight() / 2);
g2d.drawImage(img, at, this);
g2d.dispose();
}
}
}

Categories