JavaFX中的彩色图标字体

时间:2015-10-29 20:02:26

标签: java fonts javafx

我有一个JavaFX应用程序,我想在其中使用几个图标。目前,我解析所有可能有图标的文本,为特定的字符串添加一个字符,例如":icon:",然后构建TextFlow,在其中我用图像替换匹配的关键字。然后我只将TextFlow显示为Label / TextField / etc中的图形。这对我来说非常草率。有更好的解决方案吗?

我想使用自定义字体,用我想要使用的少量图标替换一些unicode字符,但图标中必须有颜色。这是可以用字体完成的吗?我可以使用CSS来为文本的特定字符着色吗?我在这里的正确道路上吗?

1 个答案:

答案 0 :(得分:3)

您可能希望使用网络字体。

此示例使用Google Material design icons font

loveyou

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

public class MixedTextAndIconFonts extends Application {
    @Override public void start(Stage stage) {
        Text i = new Text("I");
        Text love = new Text("\uE87D");
        Text u = new Text("you");
        i.setStyle("-fx-font-family: \'Indie Flower\'; -fx-font-size: 80; -fx-fill: forestgreen;");
        love.setStyle("-fx-font-family: \'Material Icons\'; -fx-font-size: 60; -fx-fill: firebrick;");
        u.setStyle("-fx-font-family: \'Indie Flower\'; -fx-font-size: 80; -fx-fill: forestgreen;");

        TextFlow textFlow = new TextFlow(
                i,
                love,
                u
        );
        textFlow.setStyle("-fx-padding: 20px; -fx-background-color: azure;");

        Scene scene = new Scene(textFlow);
        scene.getStylesheets().add("http://fonts.googleapis.com/css?family=Indie+Flower");
        scene.getStylesheets().add("http://fonts.googleapis.com/css?family=Material+Icons");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}

对于快速样本,我内联样式,但对于"真实"应用程序,您可能会使用外部CSS样式表和有意义的常量名称作为您希望包含的图标字形的unicode代码点。

更多资源

如果您搜索了其他类似资源,例如fontawesomefxicon8 webfont conversion guideicomoon.io