Friday, August 9, 2024

java: graphics2d and rotation test

 

import java.awt.BasicStroke;

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.IOException;


import javax.imageio.ImageIO;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;


public class JFrameRotate extends JFrame {


private static final long serialVersionUID = 1L;

private JPanel contentPane;


/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

JFrameRotate frame = new JFrameRotate();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

int panelWidth=600, panelHeight=600;


/**

* Create the frame.

*/

public JFrameRotate() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(0, 0, panelWidth, panelHeight);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));


setContentPane(contentPane);

loadCard();

}


// JFrame: public void paint(Graphics g)

// JPanel: protected void paintComponent(Graphics g)

@Override

public void paint(Graphics g) {

if (bImg!=null) {

//g.drawImage(bImg, xCenter, yCenter, this);

// draw the image

Graphics2D g2d = (Graphics2D) g;

g2d.drawImage(bImg, rotate(10), contentPane);

g2d.drawImage(bImg, rotate(45), contentPane);

g2d.drawImage(bImg, rotate(90), contentPane);

g2d.drawImage(bImg, rotate90(), contentPane);

}

}

int strokeImg =1, widthImg=100, heightImg=150;

int xCenter=200, yCenter=300;

BufferedImage bImg;

private void loadCard() {

bImg = new BufferedImage(widthImg,

heightImg, BufferedImage.TYPE_INT_BGR);

Graphics2D g2d = bImg.createGraphics();

g2d.setStroke(new BasicStroke(1)); // 1 pixel

// https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8

String sFName = "/images/KC.png"; // See here to setup image resources

BufferedImage img;

try {

img = ImageIO.read(getClass().getResource(sFName));

g2d.drawImage(img, strokeImg, strokeImg, widthImg-(2*strokeImg),

heightImg-(2*strokeImg), this);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private AffineTransform rotate(int degree) {


double rotationAngle=degree*Math.PI/180;

AffineTransform transform = new AffineTransform();

transform.rotate(rotationAngle, xCenter, yCenter);

//transform.rotate(rotationAngle);

transform.translate(xCenter, yCenter);

return transform;

}

/*

* 90 degree only, keep on position top left

*/

private AffineTransform rotate90() {


double rotationAngle=90*Math.PI/180;

AffineTransform transform = new AffineTransform();

transform.rotate(rotationAngle, xCenter, yCenter);

// yCenter-heightImg = horizontal position

// xCenter: vertical position

transform.translate(xCenter, yCenter-heightImg);

return transform;

}

}

No comments:

Post a Comment