2014-01-29 29 views
1

我正在製作一個使用JavaFX作爲UI的地圖編輯器和一個自定義畫布來繪製用戶將繪製地圖的組件。JavaFX canvas GraphicsContext.drawImage巨大的滯後

這是畫布組件,我在我的地圖編輯器

public class EditorEngine extends Canvas { 

    public Level level; 
    public MouseHandler mouse; 

    @SuppressWarnings("unchecked") 
    public EditorEngine(Level level, ReadOnlyDoubleProperty widthProperty, ReadOnlyDoubleProperty heightProperty) { 
     super(widthProperty.getValue(), heightProperty.getValue()); 

     this.level = level; 
     level.engine = this; 
     this.widthProperty().bind(widthProperty); 
     this.heightProperty().bind(heightProperty); 
     this.mouse = new MouseHandler(this); 

     Duration frameDuration = Duration.millis(1000/42); 

     @SuppressWarnings("rawtypes") 
     KeyFrame frame = new KeyFrame(frameDuration, new EventHandler() { 
      @Override 
      public void handle(Event event) { 
       update(); 
       render(); 
      } 
     }); 

     new Timeline(60).setCycleCount(Animation.INDEFINITE); 
     TimelineBuilder.create().cycleCount(Animation.INDEFINITE).keyFrames(frame).build().play(); 
    } 

    public int tick = 0; 

    public void update() { 
     tick++; 

     if (level != null) { 
      level.update(); 
     } 

     mouse.update(); 
    } 

    public void render() { 
     GraphicsContext g = getGraphicsContext2D(); 

     g.clearRect(0, 0, getWidth(), getHeight()); 
     g.fillRect(mouse.mx - 5, mouse.my - 5, 10, 10); //for testing and stuff 

     if (level != null) { 
      level.render(g); 
     } 

    } 
} 

嵌入但這不是哪裏出了問題正在發生。看看我的Level.draw方法

public void render(GraphicsContext g) { 
    for (int i = 0; i < w; i++) { 
     for (int j = 0; j < h; j++) { 
      if (getTile(i, j) == null) continue; 

      Tileset t = Project.current.world.getTileset(tiles[j * w + i].tileset); 

      if (t.sprite != null) { 
       g.drawImage(t.sprite.get(), tiles[index(i, j)].sprite % t.w, tiles[index(i, j)].sprite/t.w, 16, 16, i * 16, j * 16, 16, 16); 
      } else { 
       System.out.println("Warning: Tileset.sprite == null!"); 
      } 
     } 
    } 
} 

這是故障線路

g.drawImage(t.sprite.get(), tiles[index(i, j)].sprite % t.w, tiles[index(i, j)].sprite/t.w, 16, 16, i * 16, j * 16, 16, 16); 

調用此爲兩個或三個片會滯後一點,任何接近5+瓷磚完全凍結了該應用程序。我100%認爲這是問題,因爲它在沒有這條線的情況下運行100%,但一旦它加回(在調試模式下)並保存,軟件立即凍結。

會有人有任何想法,爲什麼發生這種情況?謝謝

+0

有[Java 8](https://jdk8.java.net/)的性能問題。它對Java 8更好嗎?還運行[graphicsContext.clearRect()](http://docs.oracle.com/javafx/2/api/javafx/scene/canvas/GraphicsContext.html#clearRect%28double,%20double,%20double,%20double %29)(或'fillRect')方法渲染每幀有助於性能? – jewelsea

+0

我現在實際上正在使用Java 8,並且在渲染任何東西之前我已經使用了clearrect,正如你所看到的 –

回答

0

沒關係。這是我的錯誤,我完全忽略了一些。 t.sprite是我自己的LazySprite類,一個只在需要時才從硬盤加載的sprite。事實證明,我忘記了在加載後將它的布爾值「初始化」設置爲true,所以它每隔一幀就從我的HDD中繼續加載tileset。