群里问道一个JavaFx的需求,如何显示一个圆角边框图片。总不能让原来的图片直接就做成圆角的吧,这肯定不现实。最终在stackoverflow上有大神写出了自己的方案。在此纪录在案——先膜拜一下。原话如下:
If you want to actually round the image itself, it's a bit trickier. You need to apply some code to:
- Clip the image to a rounded rectangle.
- Snapshot the clipped image.
- Store the snapshot image back in the ImageView.
- Remove the clip from the ImageView.
- Apply the drop shadow effect to the ImageView.
Then you can get something like below:
圆角图片Some code:
@FXML
public void initialize() {
// set a clip to apply rounded border to the original image.
Rectangle clip = new Rectangle(
imageView.getFitWidth(), imageView.getFitHeight()
);
clip.setArcWidth(20);
clip.setArcHeight(20);
imageView.setClip(clip);
// snapshot the rounded image.
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage image = imageView.snapshot(parameters, null);
// remove the rounding clip so that our effect can show through.
imageView.setClip(null);
// apply a shadow effect.
imageView.setEffect(new DropShadow(20, Color.BLACK));
// store the rounded image in the imageView.
imageView.setImage(image);
}
网友评论