本文以使用 ImageView
创建用户头像为例
默认样式
先看下默认样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class ImageDemo extends Application {
@Override public void start(Stage stage) throws Exception {
VBox root = new VBox(); root.setAlignment(Pos.CENTER); root.setSpacing(20);
int size = 100; ImageView cover = new ImageView(new Image(new FileInputStream("/Users/yi/Desktop/pic.png"))); cover.setFitWidth(size); cover.setFitHeight(size); root.getChildren().add(cover);
Scene scene = new Scene(root, 400, 200); scene.getStylesheets().add(this.getClass().getResource("/css/style.css").toExternalForm()); stage.setScene(scene); stage.setTitle("Image Demo"); scene.setRoot(root); stage.show(); }
public static void main(String[] args) { launch(args); } }
|
运行效果:
修改圆角
圆角效果可以使用 ImageView.clip()
方法完成:
1 2 3 4 5 6 7 8 9 10 11
| int size = 100; ImageView cover = new ImageView(new Image(new FileInputStream("/Users/yi/Desktop/pic.png"))); cover.setFitWidth(size); cover.setFitHeight(size);
int arc = 25; Rectangle clip = new Rectangle(cover.getFitWidth(), cover.getFitHeight()); clip.setArcWidth(arc); clip.setArcHeight(arc); cover.setClip(clip);
|
将圆角弧度设置为 25
后:
设置为圆形
圆形头像可以设置弧宽高为头像的宽高,即设置为 1
:
1 2 3 4 5 6 7 8 9 10 11
| int size = 100; ImageView cover = new ImageView(new Image(new FileInputStream("/Users/yi/Desktop/pic.png"))); cover.setFitWidth(size); cover.setFitHeight(size);
int arc = 100; Rectangle clip = new Rectangle(cover.getFitWidth(), cover.getFitHeight()); clip.setArcWidth(arc); clip.setArcHeight(arc); cover.setClip(clip);
|
圆形效果: