java画图旋转代码_如何在Java中旋转图像图标

旋转图像是非三角的,即使是90度也需要一定的工作量。

所以,基于几乎所有关于旋转图像的问题,我会从…

public BufferedImage rotate(BufferedImage image, Double degrees) {

// Calculate the new size of the image based on the angle of rotaion

double radians = Math.toRadians(degrees);

double sin = Math.abs(Math.sin(radians));

double cos = Math.abs(Math.cos(radians));

int newWidth = (int) Math.round(image.getWidth() * cos + image.getHeight() * sin);

int newHeight = (int) Math.round(image.getWidth() * sin + image.getHeight() * cos);

// Create a new image

BufferedImage rotate = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2d = rotate.createGraphics();

// Calculate the "anchor" point around which the image will be rotated

int x = (newWidth - image.getWidth()) / 2;

int y = (newHeight - image.getHeight()) / 2;

// Transform the origin point around the anchor point

AffineTransform at = new AffineTransform();

at.setToRotation(radians, x + (image.getWidth() / 2), y + (image.getHeight() / 2));

at.translate(x, y);

g2d.setTransform(at);

// Paint the originl image

g2d.drawImage(image, 0, 0, null);

g2d.dispose();

return rotate;

}

当您只旋转90度时,这将计算新图像所需的大小,以便能够以任何角度绘制旋转的图像。

然后它只是利用

AffineTransform

要操纵绘画发生的原点-使用这个,你会做很多。

然后,我加载图像,旋转它们并显示它们…

rkmbx.png

try {

BufferedImage original = ImageIO.read(getClass().getResource("domino.jpg"));

BufferedImage rotated90 = rotate(original, 90.0d);

BufferedImage rotatedMinus90 = rotate(original, -90.0d);

JPanel panel = new JPanel();

panel.add(new JLabel(new ImageIcon(original)));

panel.add(new JLabel(new ImageIcon(rotated90)));

panel.add(new JLabel(new ImageIcon(rotatedMinus90)));

JOptionPane.showMessageDialog(null, panel, null, JOptionPane.PLAIN_MESSAGE, null);

} catch (IOException ex) {

ex.printStackTrace();

}

我更喜欢用

ImageIO

加载图像,因为它抛出

IOException

当事情出错时,宁愿默默地失败

ImageIcon

.

您还应该将资源嵌入到应用程序的上下文中,这使得在运行时加载它们更加容易。取决于IDE和项目的设置方式,您的设置方式将发生变化,但在“大多数”情况下,您应该能够将资源直接添加到源目录(最好是子目录中),并且IDE将使您可以使用它并在导出项目时对其进行打包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值