使用Skiko和Kotlin,我想制作一个基本的动画:一个每秒自动更新文本的0到100计数器。我设法做到了,但它有问题,每次重新粉刷窗户时都会闪烁。这是代码:
import kotlinx.coroutines.*
import org.jetbrains.skija.*
import org.jetbrains.skiko.*
import javax.swing.*
public fun main() {
val window = SkiaWindow().apply {
layer.renderer = CounterRenderer()
setSize(400, 175)
isVisible = true
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
}
GlobalScope.launch {
for (i in 0..100) {
delay(1000)
window.layer.repaint()
}
}
}
public class CounterRenderer : SkiaRenderer {
private lateinit var canvas: Canvas
private var counter = 0
override fun onInit() {
}
override fun onDispose() {
}
override fun onReshape(width: Int, height: Int) {
}
override fun onRender(canvas: Canvas, width: Int, height: Int) {
this.canvas = canvas
val typeface = Typeface.makeFromName("Roboto", FontStyle.NORMAL)
val fontSize = 30F
val font = Font(typeface, fontSize)
val paint = Paint().setColor(0XFF000000.toInt())
canvas.drawString("Counter: ${counter++}", 10F, 50F, font, paint)
}
}
我尝试过用skija或skiko搜索动画的例子,但没有成功。如果你能给我举几个例子,我将不胜感激。
浏览Android Compose代码后,尤其是此类:ComposeLayer。我终于用这个代码工作了:
import kotlinx.coroutines.*
import org.jetbrains.skija.*
import org.jetbrains.skiko.*
import javax.swing.*
public fun main() {
val window = SkiaWindow().apply {
layer.renderer = CounterRenderer()
setSize(400, 175)
isVisible = true
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
}
GlobalScope.launch(Dispatchers.Main) {
for (i in 0..100) {
delay(500)
window.layer.redrawLayer()
}
}
}
public class CounterRenderer : SkiaRenderer {
private var counter = 0
private val typeface = Typeface.makeFromName("Roboto", FontStyle.NORMAL)
private val fontSize = 30F
private val font = Font(typeface, fontSize)
private val paint = Paint().setColor(0XFF000000.toInt())
override fun onInit() {
}
override fun onDispose() {
}
override fun onReshape(width: Int, height: Int) {
}
override fun onRender(canvas: Canvas, width: Int, height: Int) {
canvas.drawString("Counter: ${counter++}", 10F, 50F, font, paint)
}
}
要运行此代码,您需要安装特定的Main Dispatcher,在这种情况下,可以将其添加到gradle配置中:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.3.9")