Java 图形 : setClip vs clipRect vs repaint(int, 整数、整数、整数)

标签 java swing animation graphics2d

类似于我上一篇致歉的文章,但没有那么长篇大论。基本上我想知道当每次重绘调用只重绘屏幕的一小部分时,优化重绘到 JFrame/JPanel 的最佳选择是什么。

此外,除了重绘重载之外,我并不是 100% 了解如何实现 setClip 或 clipRect。我的理解是在重写绘画或更新时使用它们? 请参阅下面的一些代码:

public class AquaSim extends JPanel {
//variables
//other methods...
    public void paint (Graphics g) {
       super.paintComponent(g); //needed?
       Graphics2D g2d = (Graphics2D) g;

        //Draws the land area for penguins.
        g2d.setColor(new Color(121,133,60));
        g2d.fill(land);
        g2d.setColor(Color.BLUE);
        g2d.fill(sea);

        drawCreatures(g2d);
}
    public void drawCreatures(Graphics2D g2d) {
        for (Creature c : crlist) //a list of all alive creatures {
            //each creature object stores its image and coords.
            g2d.drawImage(c.createImage(txs,tys), c.getPos(1).width, c.getPos(1).height, this);
        }
    }
}

理想情况下,我宁愿不必在每个重绘请求中遍历每个生物对象,这也是写这篇文章的部分原因。我不知道是否有一种方法可以将正在绘制的当前生物发送到 Creature 类中进行绘画或覆盖绘画,以使其将自己绘制到主类中的图形对象上。 更多代码...

private class Creature implements ActionListener {
//variables & other methods
        @Override
        public void actionPerformed(ActionEvent e) {
            if (getState()!=State.DEAD) {
                move();
                repaint(); //<---Would rather set clipping area in paint/update. x,y,w,h needs to include ICON & INFO BOX.
                //repaint(gx,gy,getPos(1).width,getPos(1).height);
            }
            else anim.stop();
        }
//...


  public void move() {
    //Determines how it will move and sets where to here by updating its position that is used in drawCreatures.
    }
}

那么有什么建议是最有效的使用方法吗?请记住,重绘会被许多对象/生物调用很多次,即每秒多次,因此我不希望它在每次重绘请求时重绘屏幕上的所有内容。

最佳答案

only a small part of the screen would be redrawn.

使用repaint(....)

RepaintManager 会担心需要绘制什么,并会为您设置 Graphics 对象的剪辑。

关于Java 图形 : setClip vs clipRect vs repaint(int, 整数、整数、整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27509360/

相关文章:

javascript - 使用 CSS 和 skrollr.js 为 <body> 背景设置动画

java - MVC : how should I switch between different datasets - update or replace?

java - 在 JFXPanel 中嵌入 JavaFX Stage (Swing Embed)

java - 这个 JFileChooser 有什么问题

javascript - 如何在 Phaser Js 中逐字或逐行输入?

c++ - OpenGL 中 DirectX 文件的骨骼动画

java - 在添加数字时对 Java 数组进行排序

java - 如何在java中制作IOS应用程序?

java - Android - fragment 中两个按钮中的第二个按钮无响应

java - 从文本文件填充 JCombobox