[英]How can I move image slowly?
我想慢慢移動圖像。但是drawImage()方法只接受int值。是否有任何方法可以慢慢地移動圖片。我想讓地面向左移動一點點。
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Board extends JPanel {
private Image ground;
private Image city;
private int x = 0;
public Board() {
ground = Toolkit.getDefaultToolkit().getImage("Resources\\ground2.png");
city = Toolkit.getDefaultToolkit().getImage("Resources\\background2.png");
}
public void paint(Graphics g){
super.paint(g);
g.drawImage(ground, x--, 500, 600, 200, this);
g.drawImage(ground, x + 600, 500, 600, 200, this);
repaint();
g.drawImage(city, 0, 0, 600, 500, this);
if(x == -600){
x = 0;
}
}
}
您可以使用Swing Timer
更改x
變量並重新繪制。 將下一個代碼添加到Board
構造函數中:
Timer t = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x--;
repaint();
}
});
t.start();
還可以在paintComponent()
方法而不是paint()
進行自定義繪制:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(ground, x, 500, 600, 200, this);
g.drawImage(ground, x + 600, 500, 600, 200, this);
g.drawImage(city, 0, 0, 600, 500, this);
if (x == -600) {
x = 0;
}
}
並且不要在paint()
或paintComponent()
方法中調用repaint()
。
drawImage()
方法只接受int值。是否有任何方法可以慢慢移動圖片。
當然。 使用AffineTransform
翻譯實例 。 他們可以使用雙值。 然后,生成的圖像繪制將沿着邊緣“抖動”,以顯示看起來像是“子像素精度”的渲染。
我相信你x的四舍五入不是問題。 真正的一個是你需要使用基於時間的動畫而不是基於幀的動畫來移動。 您可以使用基於float的方法(double用於您的目的太多)或使用整數執行一些簡單的步驟。 添加成員:
private long startTime = 0;
刪除int x作為成員。
然后使用以下內容更改繪圖例程中的代碼:
public void paint(Graphics g){
super.paint(g);
long delta;
if ( startTime == 0 ) {
startTime = System.currentTimeMillis();
delta = 0;
} else {
long now = System.currentTimeMillis();
delta = now - startTime;
}
//using startTime instead of lastTime increase very slow speed accuracy
const long speed = 30; //pixel/sec
//threshold with your image width
int x = (int)((( speed * delta ) / 1000l)%600l);
//
//--- your draw code ---
//
}
瞧瞧!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.