使用Canvas的窗口进行渲染
继承Canvas,在其paint中启动原生窗口渲染,并更新其大小
例子: 这里用到了JNA的Native.getComponentPointer
class MyNativeWindow(handle :PointerByReference) {
fun start() {
// 原生代码
}
fun setSize(x:Int, y:Int) {
// 原生代码
}
}
class MyNativeComponent() :Canvas() {
private var initialized = false
private var nativeWindow: MyNativeWindow? = null
private var lastSize: Dimension? = null
override fun paint(g: Graphics?) {
val size = this.size
if (size != lastSize) {
lastSize = size
if (nativeWindow != null) {
this.updateSize()
}
}
if (!initialized) {
initialized = true
Thread {
nativeWindow(PointerByReference(Native.getComponentPointer(this))).start()
this.updateSize()
}.start()
}
}
private fun updateSize() {
nativeWindow?.setSize(lastSize!!.width, lastSize!!.height)
}
}
参考实例: https://github.com/Casterlabs/Webview/blob/main/src/main/java/dev/webview/Webview.java#L41
特点:
- 可作为控件使用
- 需要原生窗口支持在非主线程中运行
作为子窗口(Windows)
这里用到了jna-platform的User32.INSTANCE.SetParent
User32.INSTANCE.SetParent(HWND(pWin),HWND(getComponentPointer(c)))
其中c为Canvas,pWin为原生窗口指针
特点:
- 仅支持Windows
- 需要窗口无边框
- 无需为原生窗口提供HANDLE