如何在 tornadofx imageview 中显示新图像?

How do I display a new image in tornadofx imageview?

我想在 imageview 中显示 WritableImage,但我希望该图像在用户从文件浏览器加载新文件时发生变化。我知道有一个 bind() 函数用于随时间变化的字符串,但我找不到类似的图像选项。我可以解决与默认加载图像大小相同的图像的问题(通过像素写入),但这仅在它们大小相同时才有效,因为我无法修改我显示的图像的大小。 到目前为止我的 Kotlin 代码:

class PhotoView : View("Preview") {

val mainController: mainController by inject()

override val root = hbox {
    imageview{
        image = mainController.moddedImg
    }
    hboxConstraints {
        prefWidth = 1000.0
        prefHeight = 1000.0
    }
}


class ControlView: View(){

val mainController: mainController by inject()

override val root = hbox{
    label("Controls")
    button("Make BW!"){
        action{
            mainController.makeBW()
        }
    }
    button("Choose file"){
        action{
            mainController.setImage()
            mainController.update()
        }
    }

}
}

class mainController: Controller() {

private val ef = arrayOf(FileChooser.ExtensionFilter("Image files (*.png, *.jpg)", "*.png", "*.jpg"))
private var sourceImg=Image("pic.png")
var moddedImg = WritableImage(sourceImg.pixelReader, sourceImg.width.toInt(), sourceImg.height.toInt())

fun setImage() {
    val fn: List<File> =chooseFile("Choose a photo", ef, FileChooserMode.Single)
    sourceImg = Image(fn.first().toURI().toString())
    print(fn.first().toURI().toString())
}

fun makeBW() {
    val pixelReader = sourceImg.pixelReader
    val pixelWriter = moddedImg.pixelWriter

    // Determine the color of each pixel in a specified row
    for (i in 0 until sourceImg.width.toInt()) {
        for (j in 0 until sourceImg.height.toInt()) {
            val color = pixelReader.getColor(i, j)
            pixelWriter.setColor(i, j, color.grayscale())
        }
    }
}

fun update() {
    val pixelReader = sourceImg.pixelReader
    val pixelWriter = moddedImg.pixelWriter

    // Determine the color of each pixel in a specified row
    for (i in 0 until sourceImg.width.toInt()) {
        for (j in 0 until sourceImg.height.toInt()) {
            val color = pixelReader.getColor(i, j)
            pixelWriter.setColor(i, j, color)
        }
    }
}
}

ImageView 有一个 属性 可以绑定的图像:

class PhotoView : View("Preview") {
    val main: MainController by inject()

    val root = hbox {
        imageview { imageProperty().bind(main.currentImageProperty) }
        ...
    }
    ...
}

class MainController : Controller() {
    val currentImageProperty = SimpleObjectProperty<Image>(...)
    var currentImage by currentImageProperty  // Optional
    ...
}

从那里开始,只要您在 MainController 中设置 currentImage,它就会在 PhotoView 中更新。