1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DemoRotations extends JPanel {
Image image = loadImage();
public DemoRotations() {
setBackground(Color.BLACK);
setBorder(BorderFactory.createLineBorder(Color.GREEN, 5)); // bordure de 5px
}
private Image loadImage() {
try(InputStream resourceStream = DemoRotations.class.getResourceAsStream("suricate.jpg")) {
return ImageIO.read(resourceStream);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
return null;
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
// la ligne suivante, c'est juste pour prendre en compte la bordure, pour que x=50 soit bien à 50px du bord
((Graphics2D)g).translate(getInsets().left, getInsets().top);
g.setColor(Color.RED);
// affichage normal (sans rotation)
g.drawImage(image, 50,50, this);
g.drawRect(50 , 50, image.getWidth(this), image.getHeight(this));
// rotation 90 clockwise
rotateImage(g, image, 200, 50, 90);
g.drawRect(200 , 50, image.getWidth(this), image.getHeight(this));
// rotation 45 clockwise
rotateImage(g, image, 350, 50, 45);
g.drawRect(350 , 50, image.getWidth(this), image.getHeight(this));
// rotation 90 counterclockwise
rotateImage(g, image, 50, 200, -90);
g.drawRect(50 , 200, image.getWidth(this), image.getHeight(this));
// rotation 180 clockwise
rotateImage(g, image, 200, 200, 180);
g.drawRect(200 , 200, image.getWidth(this), image.getHeight(this));
// rotation 60 counterclockwise
rotateImage(g, image, 350, 200, -60);
g.drawRect(350 , 200, image.getWidth(this), image.getHeight(this));
}
/**
* Affiche dans g une image tournée de angle aux coordonnées x et y
* @param g contexte graphique
* @param image image
* @param x x
* @param y y
* @param angle angle en degrés
*/
private void rotateImage(Graphics g, Image image, int x, int y, double angle) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.transform(AffineTransform.getRotateInstance(Math.toRadians(angle), x + image.getWidth(this)/2, y + image.getHeight(this)/2));
g2d.drawImage(image, x, y, this);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new DemoRotations();
frame.add(content);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager