Java 图形2D在黑白背景上旋转

Java 图形2D在黑白背景上旋转,java,background,rotation,graphics2d,Java,Background,Rotation,Graphics2d,我有一个在g2组件上绘制旋转图片的函数,但由于某些原因,我不能给它任何彩色背景。。。 我试图使用方法.setColor()和.setBackground(),但没有用。 我在这里见过类似的案例 但这并没有真正起作用。以下是我的功能: public void rotateImage1(double degrees, ImageObserver o){ double sin = Math.abs(Math.sin(Math.toRadians(degrees)));

我有一个在g2组件上绘制旋转图片的函数,但由于某些原因,我不能给它任何彩色背景。。。 我试图使用方法.setColor()和.setBackground(),但没有用。 我在这里见过类似的案例 但这并没有真正起作用。以下是我的功能:

        public void rotateImage1(double degrees, ImageObserver o){

        double sin = Math.abs(Math.sin(Math.toRadians(degrees)));
        double cos = Math.abs(Math.cos(Math.toRadians(degrees)));
        ImageIcon icon = new ImageIcon(this.spiral);
        int w = icon.getIconWidth();
        int h = icon.getIconHeight();
        int neww = (int)Math.floor(w*cos+h*sin);
        int newh = (int)Math.floor(h*cos+w*sin);
        BufferedImage blankCanvas = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
        if(PhotoEdit.black)
            g2.setColor(Color.BLACK);
        else
            g2.setColor(Color.WHITE);
        g2.translate((neww-w)/2, (newh-h)/2);
        g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);

        g2.drawImage(this.spiral, 0, 0, o);
        this.spiral = blankCanvas;
}

PhotoEdit.black是一个布尔变量,如果用户选择了带有黑色背景的复选框选项,则该变量为真。

您正在图形中设置颜色,但未将其绘制到面板

您可以使用
g2.setColor(…)
g2.fillRect(…)
并指定覆盖整个面板的坐标,然后在顶部绘制图像


fillRect的文档:

你说的“我不能给它任何彩色背景”是什么意思。当你尝试这样做时,具体发生了什么?我的意思是,当我将图片旋转45度时,由于旋转,我得到了这些空白。我想给它们上色。通常它们是白色的,所以听起来问题不在于绘制旋转对象的方法,而在于绘制背景的方式。你确定每次旋转对象时都在设置正确的颜色并重新绘制背景吗?是的,每次我要旋转时都会调用此方法,并且颜色设置在这里,我错了吗?考虑到这个方法之外的背景,我没有写更多的东西。我想把这些空白区域涂上颜色,这样在保存时,颜色会与图像保持一致。