2012-12-05 102 views
3

我正在嘗試使用ScrollEvent將包含RectangleText對象的對象縮放放大和縮小。我無法從滾動的三角洲獲得正確的比例。下面的代碼是我目前所擁有的。任何幫助將不勝感激。使用滾動事件放大和縮小使用滾動事件

感謝

import javafx.application.Application; 
import javafx.event.EventHandler; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.input.ScrollEvent; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 

// demonstrates scaling a test pane with content in it. 
public class ScaleTest extends Application { 
    Group page; 
    double textScale =1.0; 
    public static void main(String[] args) { 
     launch(); 
    } 

    @Override 
    public void start(Stage stage) throws Exception { 
     stage.setTitle("scale test"); 
     Group root = new Group(); 
     page= new Group(); 
     Rectangle r = new Rectangle(300,300); 
     Text t = new Text("asodjoijdjiasjdoijaisjdijasijdiajsidjoiasjiodjiajosijdiojaisjdoijaoisjdiojaoisjdjaoisjdiojsoidj\njdoasijdoajsoidjoaisjoidjaoisjdiojs"); 
     t.setFill(Color.FLORALWHITE); 
     t.setWrappingWidth(280); 
     t.setX(10); 
     t.setY(20); 
     page.getChildren().addAll(r,t); 
     root.getChildren().add(page); 
     Scene scene = new Scene(root,800,600); 
     this.setSceneEvents(scene); 
     stage.setScene(scene); 
     stage.show(); 
    } 
    private void setSceneEvents(final Scene scene) { 
     //handles mouse scrolling 
     scene.setOnScroll(
       new EventHandler<ScrollEvent>() { 
        @Override 
        public void handle(ScrollEvent event) { 
         double xscale = page.getScaleX() * event.getDeltaY()/35; 
         double yscale= page.getScaleY() * event.getDeltaY()/35; 
         System.out.println("xscale: "+ xscale); 
         System.out.println("yscale: "+ yscale); 
         //page.setScaleX(page.getScaleX() * event.getDeltaY()/35); 
         // page.setScaleY(page.getScaleY() * event.getDeltaY()/35); 
         event.consume(); 
        } 
       }); 

    } 
} 

回答

8

|移動deltaY |適用於所有滾動事件。還要注意,deltaY對於向下滾動是負的,並且縮放比例總是被標準化爲1.0。所以我建議使用決定縮放的「縮放因子」。嘗試類似:

private void setSceneEvents(final Scene scene) { 
    //handles mouse scrolling 
    scene.setOnScroll(
      new EventHandler<ScrollEvent>() { 
       @Override 
       public void handle(ScrollEvent event) { 
       double zoomFactor = 1.05; 
       double deltaY = event.getDeltaY(); 
       if (deltaY < 0){ 
        zoomFactor = 2.0 - zoomFactor; 
       } 
       System.out.println(zoomFactor); 
       page.setScaleX(page.getScaleX() * zoomFactor); 
       page.setScaleY(page.getScaleY() * zoomFactor); 
       event.consume(); 
       } 
      }); 

    }