Reputation: 7255
I am facing a problem flipping horizontally or vertically an Image in JavaFX Canvas
.
Scale in theory:
flip here (scale(-1,1) ) | here it was
_ _ _ _ _|_ _ _ _ _
|
flip here (scale(-1,-1) ) | fliped here( scale(1,-1) )
Here are some lines of the method which is called about 30 times per second.So i am using the method gc.scale(-1,0)
to flip the image horizontally but everything lags.How can i do that?
public void drawMethod{
//....
gc.drawImage(lightBlueLight, 0, 0); // where lightBlueLight is an `Image`
//...
}
For example in Swing
i was using this way to reflect text-> Reflecting text in java
But in JavaFX i am new to transformations so i don't know what is the way to do this(if possible i want to know the best way it terms of cpu usage):
Sample image(what i have):
i want to draw it on canvas as:
Upvotes: 3
Views: 8986
Reputation: 159291
In addition to a scale, you also need a translate otherwise it will just flip around the left edge of the canvas and show nothing.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class Flipper extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Canvas canvas = new Canvas(300, 300);
Image image = new Image("https://i.sstatic.net/ySbuj.png");
double xoff = 15;
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.save();
gc.translate(image.getWidth() + xoff * 2, 0);
gc.scale(-1, 1);
gc.drawImage(image, xoff, 0);
gc.restore();
gc.drawImage(image, xoff, 0);
stage.setScene(new Scene(new Group(canvas)));
stage.show();
}
}
Upvotes: 4
Reputation: 78
Try this :
public void draw(GraphicsContext g){
//(javafx.scene.image.Image,
// sourceX,sourceY, sourceWidth,sourceHeight,
//outputX,outputY,outputWidth,outputHeight);
g.drawImage(RESOURCE, 0, 0, RESOURCE.getWidth(), RESOURCE.getHeight(), RESOURCE.getWidth(),0,-RESOURCE.getWidth(),RESOURCE.getHeight());
}
by inputting negative value as output width/height value will flip the image. (remember to adjust your output X and Y accordingly)
I run the code with 30 fps,it runs smoothly.
Upvotes: 4