我刚刚开始学习在Java中逐像素制作图形。但是,我不知道如何写像素。它只是显示灰色屏幕。有人可以帮我解决这个问题吗?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pixelprogramming;
import java.util.Random;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* @author Ish Chhabra
*/
public class PixelProgramming extends Application {
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.getChildren().add(new ImageView(createImage(300, 250)));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public Image createImage(int width, int height) {
WritableImage img = new WritableImage(width, height);
PixelWriter pw = img.getPixelWriter();
Random rnd = new Random();
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
pw.setColor(x, y, Color.rgb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
}
}
return img;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}