图形上下文在第一次绘制时未对齐

2022-09-03 15:37:57

我一直在为另一个问题寻找答案,并遇到了一个我以前从未见过的怪异问题......

基本上,该程序使用a来提供元素的平移,缩放和旋转,简单的东西,之前已经完成了一千次AffineTransformGraphics

问题是,当屏幕首次出现时,输出不在应有的位置,但是一旦我触摸其中一个控件(调整其中一个幻灯片),它就会跳到正确的位置。

SliderSlider

根据屏幕截图,内容似乎被其他控件的数量放错了位置。Graphics

如果我从 GUI 中删除控件,它将出现在正确的位置(在中心)。如果我调整窗口大小,它不会解决问题,它只会在其中一个滑块触发时修复...repaintDrawPane

我已将诊断添加到输出中,并且所有值都相同 - 也就是说,当程序首次启动时以及当我将所有滑块值调整为初始值时,它们将打印相同的值。

如果我从 中删除 和 调用,它不会修复它。如果我删除 ,则在面板更新之前,方块最初不会绘制(它被绘制在屏幕之外)setRotationsetScaleAffineTransformsetTranslation

如果我使用 而不是 ,则结果相同(是的,我在方法退出之前重置转换;))Graphics2D g2d = (Graphics)g;g.create()paintComponent

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Parker {

    public static void main(String[] args) {
        new Parker();
    }

    public Parker() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new ControlPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ControlPane extends JPanel {

        private JSlider slider; //declare slider
        private DrawPane myPanel; 
        public ControlPane() {
            setLayout(new BorderLayout());
            myPanel = new DrawPane();
            myPanel.setBackground(Color.cyan); //change background color

            slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 100);// restrains the slider from scaling square to 0-300 pixels
            slider.setMajorTickSpacing(20); //will set tick marks every 10 pixels
            slider.setPaintTicks(true); //this actually paints the ticks on the screen

            slider.addChangeListener(
                    new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            myPanel.setScale(slider.getValue()); //Wherever you set the slider, it will pass that value and that will paint on the screen
                        }
                    }
            );

            JSlider rotate = new JSlider(SwingConstants.VERTICAL, 0, 720, 0);
            rotate.setMajorTickSpacing(20); //will set tick marks every 10 pixels
            rotate.setPaintTicks(true); //this actually paints the ticks on the screen

            rotate.addChangeListener(
                    new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            JSlider slider = (JSlider) e.getSource();
                            myPanel.setAngle(slider.getValue()); 
                        }
                    }
            );
            add(slider, BorderLayout.WEST);
            add(rotate, BorderLayout.EAST);

            add(myPanel);

            slider.setValue(0);
            slider.setValue(100);
            rotate.setValue(0);

        }

    }

    public class DrawPane extends JPanel {

        private double scale = 1;
        private double angle = 0;

        private final int rectWidth = 20;
        private final int rectHeight = 20;


        @Override
        protected void paintComponent(Graphics g)//paints obj on the screen
        {
            super.paintComponent(g); //prepares graphic object for drawing

            int originX = getWidth() / 2; 
            int originY = getHeight() / 2;

            int xOffset = -(rectWidth / 2);
            int yOffset = -(rectHeight / 2);

            g.setColor(Color.BLACK);
            Graphics2D g2d = (Graphics2D) g.create();
            AffineTransform at = new AffineTransform();
            at.translate(originX, originY);
            g2d.setTransform(at);
            g2d.scale(scale, scale);
            g2d.rotate(Math.toRadians(angle), 0, 0);
            g2d.fillRect(xOffset, yOffset, rectWidth, rectHeight);
            g2d.dispose();

            g.setColor(Color.RED);
            g.drawRect(originX + xOffset, originY + yOffset, rectWidth, rectWidth);
        }

        public void setAngle(double angle) {
            this.angle = angle;
            repaint();
        }

        public void setScale(int scale) {
            // Scaling is normalized so that 1 = 100%
            this.scale = (scale / 100d);
            repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

基本上,由于某种原因,上下文似乎在第一次绘制时没有得到适当的翻译,我不知道为什么......Graphics

ps-在Windows 7 pps下在Java 6和Java 7
上进行测试-我还尝试在屏幕可见之前将初始缩放和旋转设置为其他值,结果相同

系统属性

awt.toolkit=sun.awt.windows.WToolkit
file.encoding=UTF-8
file.encoding.pkg=sun.io
file.separator=\
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
java.awt.printerjob=sun.awt.windows.WPrinterJob
java.class.path=C:\DevWork\personal\java\projects\wip\SystemProperties\build\classes
java.class.version=51.0
java.endorsed.dirs=C:\Program Files\Java\jdk1.7.0_51\jre\lib\endorsed
java.ext.dirs=C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext;C:\Windows\Sun\Java\lib\ext
java.home=C:\Program Files\Java\jdk1.7.0_51\jre
java.io.tmpdir=C:\Users\shane\AppData\Local\Temp\
java.runtime.name=Java(TM) SE Runtime Environment
java.runtime.version=1.7.0_51-b13
java.specification.name=Java Platform API Specification
java.specification.vendor=Oracle Corporation
java.specification.version=1.7
java.vendor=Oracle Corporation
java.vendor.url=http://java.oracle.com/
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
java.version=1.7.0_51
java.vm.info=mixed mode
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vm.specification.name=Java Virtual Machine Specification
java.vm.specification.vendor=Oracle Corporation
java.vm.specification.version=1.7
java.vm.vendor=Oracle Corporation
java.vm.version=24.51-b03
os.arch=amd64
os.name=Windows 7
os.version=6.1
path.separator=;
sun.arch.data.model=64
sun.cpu.endian=little
sun.cpu.isalist=amd64
sun.desktop=windows
sun.io.unicode.encoding=UnicodeLittle
sun.java.command=systemproperties.SystemProperties
sun.java.launcher=SUN_STANDARD
sun.jnu.encoding=Cp1252
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
sun.os.patch.level=Service Pack 1
user.country=AU
user.dir=C:\DevWork\personal\java\projects\wip\SystemProperties
user.home=C:\Users\shane
user.language=en
user.name=shane
user.script=
user.timezone=
user.variant=

更新

如果我使用...

g2d.translate(originX, originY);
g2d.scale(scale, scale);
g2d.rotate(Math.toRadians(angle), 0, 0);

而不是 ,它工作正常。我注意到,无论我如何使用(仅平移,仅旋转,仅缩放)我似乎都能得到相同的结果AffineTransformAffineTransform

使用示例图像进行了更新

显示调整大小框架的示例...

ZoomSpinResizeFrame

nb 矩形的最后一个位置偏移是下面提到的MouseListener

但是,如果我向 中添加一个(在类内或通过实例在外部)并调用 ,它会正确重新对齐:PMosueListenerDrawPanemyPanelrepaintmouseClicked

更新

如果我翻译 a ,请使用以下内容Shape

AffineTransform at = new AffineTransform();
at.translate(originX, originY);
at.scale(scale, scale);
at.rotate(Math.toRadians(angle), 0, 0);
g2d.setTransform(at);

Rectangle2D rect = new Rectangle2D.Double(xOffset, yOffset, rectWidth, rectHeight);
Shape shape = at.createTransformedShape(rect);

System.out.println(rect.getBounds());
System.out.println(shape.getBounds());

生成的输出与预期一致,但(图形)输出仍然错误...


答案 1

与传递给的图形上下文相关联的并不总是标识转换。由于不清楚的原因,该条目最初和调整封闭框架大小时具有该值。简单来说,可以修改 提供的副本。AffineTransformpaintComponent()m1238.0g.create()

Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = g2d.getTransform();
at.translate(originX, originY);
g2d.setTransform(at);
g2d.scale(scale, scale);
g2d.rotate(Math.toRadians(angle), 0, 0);
g2d.fillRect(xOffset, yOffset, rectWidth, rectHeight);
g2d.dispose();

附录:正如@MadProgrammer所说,“如果我从GUI中删除控件,它似乎......在市中心。实际上,观察到的水平偏移恰好是 in 的首选宽度。我怀疑在调整大小后调整原点以更容易地满足Concept#paintAll()合约:“图形上下文的原点,其坐标点,是该组件的左上角。sliderBorderLayout.WEST(0, 0)


答案 2

推荐