计算单元格大小并绘制它们之间的线条

Alo*_*iak 7 java graphics

我想绘制一个网格并在单元格中绘制东西(为了保持简单,只需填充它们).总的来说,我只是在一些面板尺寸上才能使用它,单元格距离它应该放置的位置大约1个像素(重叠线).TBH我还没有做足够的计算以便自己找到答案,所以我为此道歉,我真的不太确定如何处理这个"bug".

无论如何,这是代码:

public class Gui extends JFrame {

public static void main(String[] args) {
    new Gui().setVisible(true);
}

public Gui() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    add(new JPanel() {
        public static final int SIZE = 3;
        /** Line thickness ratio to a block */
        public static final float LINE_THICKNESS = 0.1f;

        /** @return the width of a block. */
        protected final int getBlockWidth() {
            return getWidth() / SIZE;
        }

        /** @return the height of a block. */
        protected final int getBlockHeight() {
            return getHeight() / SIZE;
        }

        /**  @return the width of a cell. */
        protected final int getCellWidth() {
            return (int) Math.ceil(getBlockWidth()*(1-LINE_THICKNESS));
        }

        /** @return the height of a cell. */
        protected final int getCellHeight() {
            return (int) Math.ceil(getBlockHeight()*(1-LINE_THICKNESS));
        }

        @Override
        public void paintComponent(Graphics g) {
            g.setColor(new Color(0, 0, 255, 100));
            int lineWidth = (int) (LINE_THICKNESS * getBlockWidth());
            int lineHeight = (int) (LINE_THICKNESS * getBlockHeight());
            for(int i = 0; i <= SIZE; i++) {
                g.fillRect(i * getBlockWidth() - lineWidth / 2, 0, lineWidth, getHeight());
                g.fillRect(0, i * getBlockHeight() - lineHeight/2, getWidth(), lineHeight);
            }
            g.setColor(new Color(255, 0, 0, 100));
            for(int i = 0; i < SIZE; i++) {
                for(int j = 0; j < SIZE; j++) {
                    int x = j * getBlockWidth() + lineWidth/2;
                    int y = i * getBlockHeight() + lineHeight/2;
                    Graphics temp = g.create(x, y, getCellWidth(), getCellHeight());
                    drawCell(temp, i, j);
                }
            }
        }

        private void drawCell(Graphics g, int i, int j) {
            g.fillRect(0, 0, getCellWidth(), getCellHeight());
        }
    });
    setLocation(new Point(500, 200));
    setSize(new Dimension(600, 600));
}
}
Run Code Online (Sandbox Code Playgroud)

如果你运行它,你可能会看到我的意思.我想不出一个很好的解释.起初我以为我必须在x和y之间添加+ 1,因为我想在线旁边绘制,但这(显然)只是将问题转移到另一边.

使用更大的SIZE(如30)运行它会给我另一个错误,它为侧面提供了开放空间.我知道(或假设)这是因为我使用的是整数,但它并没有太大的交易.但总是欢迎提供更好的方法(总的来说).

Dar*_*usz 4

有多种方法可以解决这个问题。我不会给你代码,因为我相信(根据你提出问题的方式)你是那些喜欢自己思考和解决问题的人之一。

首先:先画出整个面板的背景,然后画出线条。不会有任何白线,绘图速度也会稍微快一些。

第二种方法:绘图的顺序很重要。您可以安全地先绘制背景(即使它重叠),然后用边框覆盖它。

第三种方法:不要使用整数。使用浮点数或双精度数。你所有的烦恼都会消失。

第四种方式:计算余数。您可以预测何时绘制线条,何时绘制线条,请考虑一下。预测它并适当地绘制。