9

画像を回転させようとしています。をJInternalFrame含む がありJLabelます。ラベルには画像が含まれています。画像を回転させた後、内部フレームのサイズを変更する必要があります。私が現在持っているコードは画像を回転させますが、画像の端に黒があり、中心がずれています。これを修正する方法について何か提案はありますか?

public void rotateIcon(int angle)
{
        int w = theLabel.getIcon().getIconWidth();
        int h = theLabel.getIcon().getIconHeight();
        int type = BufferedImage.TYPE_INT_RGB;  // other options, see api

        BufferedImage DaImage = new BufferedImage(h, w, type);
        Graphics2D g2 = DaImage.createGraphics();

        double x = (h - w)/2.0;
        double y = (w - h)/2.0;
        AffineTransform at = AffineTransform.getTranslateInstance(x, y);

        at.rotate(Math.toRadians(angle), w/2.0, h/2.0);
        g2.drawImage(new ImageIcon(getData()).getImage(), at, theLabel);
        g2.dispose();

        theLabel.setIcon(new ImageIcon(DaImage));
        this.setSize(DaImage.getWidth(),DaImage.getHeight()); //resize the frame
}
4

4 に答える 4

18

三角法を使用して正しい幅/高さを決定し、透明度を使用して黒い領域を防ぐ必要があります。変換が間違っていると思います。これにより、中心がずれています。

これを試して:

public static BufferedImage rotate(BufferedImage image, double angle) {
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth(), h = image.getHeight();
    int neww = (int)Math.floor(w*cos+h*sin), newh = (int) Math.floor(h * cos + w * sin);
    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();
    g.translate((neww - w) / 2, (newh - h) / 2);
    g.rotate(angle, w / 2, h / 2);
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
}

private static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();
}

http://flyingdogz.wordpress.com/2008/02/11/image-rotate-in-java-2-easier-to-use/から

于 2010-11-11T16:36:44.803 に答える
4

Rotated Iconを使用してみてください。

于 2010-11-11T16:20:33.527 に答える
0

変更すると役立ちますか:

BufferedImage DaImage = new BufferedImage(height, width, type);

に:

BufferedImage DaImage = new BufferedImage(**width, height**, type);?

于 2010-11-11T16:26:52.930 に答える