nanogui-experiments/nanogui_customwidget.py

84 lines
2.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import nanogui
from nanogui import glfw
from nanogui import BoxLayout, Color, Label, Orientation, Screen, Widget, Window, Vector2i
from nanogui.nanovg import LerpRGBA, RGBAf, RGB
class CustomWidget(Widget):
def __init__(self, parent, size=(100, 100), color=Color(192, 0, 0, 255)):
super().__init__(parent)
self._size = size
self.color = RGBAf(color.r, color.g, color.b, color.w)
def preferred_size(self, ctx):
return Vector2i(self._size)
def draw(self, ctx):
pos = self.position()
size = self.size()
ctx.BeginPath()
ctx.Rect(pos[0], pos[1], size[0], size[1])
bg = LerpRGBA(RGB(64, 64, 64), self.color, 0.3)
ctx.FillColor(bg)
ctx.Fill()
ctx.BeginPath()
ctx.StrokeWidth(5.0)
ctx.StrokeColor(self.color)
ctx.Rect(
pos[0] + size[0] / 4.0,
pos[1] + size[1] / 4.0,
size[0] / 2.0,
size[1] / 2.0,
)
ctx.Stroke()
ctx.ClosePath()
class CustomWidgetApp(Screen):
def __init__(self, size=(400, 300)):
super().__init__(size, "NanoGUI CustomWidget")
self.win = Window(self, "Demo Window")
self.win.set_layout(BoxLayout(Orientation.Vertical, margin=20, spacing=20))
self.resize_event(size)
Label(self.win, "NanoGUI CustomWidget Demo", "sans-bold")
_ = CustomWidget(self.win, (200, 100))
self.draw_all()
self.set_visible(True)
self.perform_layout()
def resize_event(self, size):
self.win.set_fixed_size(size)
self.win.set_size(size)
self.win.center()
self.win.perform_layout(self.nvg_context())
super().resize_event(size)
return True
def keyboard_event(self, key, scancode, action, modifiers):
if super().keyboard_event(key, scancode, action, modifiers):
return True
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
self.set_visible(False)
return True
return False
if __name__ == "__main__":
import gc
nanogui.init()
app = CustomWidgetApp()
nanogui.mainloop(refresh=1 / 60.0 * 1000)
del app
gc.collect()
nanogui.shutdown()