1
我需要做什麼:信可視化TilePane JavaFX中
我想任何字符的每個像素寫一些代碼可視化。我決定它的最佳方式是將像素顯示爲Tile Pane中的矩形。因此,這是效果,我需要達到:
什麼是我的問題:
我寫了一些代碼由text1
採取snaphost使其並將其保存爲WritableImage
。然後我使用PixelReader
通過argb
方法讀取此圖像的每個像素。在循環中,每個整數rgb值大於TRESHOLD(更亮)時,添加具有白色背景的新瓦片。除非我添加黑色背景的瓷磚。可是,我還是錯了我的想法,我得到這樣的效果:
有我的代碼:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
//Create single letter string
String letter = "a";
//Create new text
Text text1 = new Text(letter);
//Set font for text
text1.setFont(Font.font("Calibri", FontWeight.NORMAL, 12));
//Save text1 as writable image
WritableImage newImg = text1.snapshot(null, null);
//Take bounds of letter
int imgHeight = (int) newImg.getHeight();
int imgWidth = (int) newImg.getWidth();
//Create pixel reader from newImg
PixelReader reader = newImg.getPixelReader();
//This is for preview image
ImageView imgPreview = new ImageView(newImg);
//Create tilePane
TilePane tilePane = new TilePane();
//New group with tilePane inside
Group display = new Group(tilePane);
//Bg color
tilePane.setStyle("-fx-background-color: gray;");
//Small gaps between tiles
tilePane.setHgap(2);
tilePane.setVgap(2);
//Set quantity of columns equals image width
tilePane.setPrefColumns(imgWidth);
//Set quantity of rows equals image height
tilePane.setPrefRows(imgHeight);
//Here I set tolerance treshold
int TOLERANCE_THRESHOLD = 0xf0;
for (int x = 0; x < imgWidth; x++) {
for (int y = 0; y < imgHeight; y++) {
int argb = reader.getArgb(x, y);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if (r >= TOLERANCE_THRESHOLD
&& g >= TOLERANCE_THRESHOLD
&& b >= TOLERANCE_THRESHOLD) {
tilePane.getChildren().add(createElement(Color.WHITE));
}
else tilePane.getChildren().add(createElement(Color.BLACK));
}
}
// Create new stage
Stage stage = new Stage();
//Create new group
Group grupa = new Group();
Scene scene = new Scene(grupa, 400, 300, Color.GRAY);
grupa.getChildren().addAll(display);
stage.setScene(scene);
stage.show();
}
private Rectangle createElement(Color color) {
Rectangle rectangle = new Rectangle(15, 15);
//rectangle.setStroke(Color.ORANGE);
rectangle.setFill(color);
return rectangle;
}
public static void main(String[] args) {
launch(args);
}
}
我做錯了嗎?馬比是其他方式來採取這種效果?
尼斯項目:) – GOXR3PLUS