實作步驟: 1、定義FlipView物件。包含以下屬性:
複製代碼代碼如下:
//正面視圖
public Node frontNode;
//反面視圖
public Node backNode;
//是否翻轉
boolean flipped = false;
//翻轉角度
DoubleProperty time = new SimpleDoubleProperty(Math.PI / 2);
//正面翻轉特效
PerspectiveTransform frontEffect = new PerspectiveTransform();
//反面翻轉特效
PerspectiveTransform backEffect = new PerspectiveTransform();
create方法傳回需要顯示的內容:
複製代碼代碼如下:
private void create() {
time.addListener(new ChangeListener() {
@Override
public void changed(ObservableValue<? extends Number> arg0,
Number arg1, Number arg2) {
setPT(frontEffect, time.get());
setPT(backEffect, time.get());
}
});
anim.getKeyFrames().addAll(frame1, frame2);
backNode.visibleProperty().bind(
Bindings.when(time.lessThan(0)).then(true).otherwise(false));
frontNode.visibleProperty().bind(
Bindings.when(time.lessThan(0)).then(false).otherwise(true));
setPT(frontEffect, time.get());
setPT(backEffect, time.get());
frontNode.setEffect(frontEffect);
backNode.setEffect(backEffect);
getChildren().addAll(backNode, frontNode);
}
以上程式碼要注意的是: 隨著time值的變化frontEffect和backEffect的值也會隨著變換。 2.PerspectiveTransform特效的實作使用了Math.sin()和Math.cos()方法模擬3D角度變換。 具體實現如下:
複製代碼代碼如下:
private void setPT(PerspectiveTransform pt, double t) {
double width = 200;
double height = 200;
double radius = width / 2;
double back = height / 10;
pt.setUlx(radius - Math.sin(t) * radius);
pt.setUly(0 - Math.cos(t) * back);
pt.setUrx(radius + Math.sin(t) * radius);
pt.setUry(0 + Math.cos(t) * back);
pt.setLrx(radius + Math.sin(t) * radius);
pt.setLry(height - Math.cos(t) * back);
pt.setLlx(radius - Math.sin(t) * radius);
pt.setLly(height + Math.cos(t) * back);
}
3.角度變換在1秒的時間內從3.14/2變換到-3.14/2。
複製代碼代碼如下:
KeyFrame frame1 = new KeyFrame(Duration.ZERO, new KeyValue(time,
Math.PI / 2, Interpolator.LINEAR));
KeyFrame frame2 = new KeyFrame(Duration.seconds(1),
new EventHandler() {
@Override
public void handle(ActionEvent event) {
flipped = !flipped;
}
}, new KeyValue(time, -Math.PI / 2, Interpolator.LINEAR));
4、FlipView物件的建立:透過建構函式可以很方便的創建FlipView物件.
複製代碼代碼如下:
ImageView image1 = new ImageView(new Image(getClass()
.getResourceAsStream("lion1.png")));
ImageView image2 = new ImageView(new Image(getClass()
.getResourceAsStream("lion2.png")));
FlipView flip = new FlipView(image1, image2);
5、效果圖: