Thursday, August 26, 2021

kv 42 perspective transform




#galaxy.py

from kivy.app import App
from kivy.graphics import Line
from kivy.metrics import dp
from kivy.properties import NumericProperty
from kivy.uix.widget import Widget


class Galaxy(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.n_vlines = 7
        self.space_vlines = dp(100)
        with self.canvas:
            self.vlines = []
            for i in range(self.n_vlines):
                vline = Line(points=(0,0,0,100))
                self.vlines.append(vline)

    def on_size(self, *args):
        start_x = self.center_x - int(self.n_vlines/2)*self.space_vlines
        for i in range(self.n_vlines):
            x = start_x+self.space_vlines*i
            x1, y1, x2, y2 = x, 0, x, self.height

            x1, y1 = self.perspective_transform(x1, y1)
            x2, y2 = self.perspective_transform(x2, y2)

            self.vlines[i].points = (x1, y1, x2, y2)

    def perspective_transform(self, x, y):
        #return x, y
        tx = (self.height-y)/self.height*(self.center_x-x)
        return self.center_x-tx, 0.8*y


class GalaxyApp(App):
    pass


GalaxyApp().run()

------------------
#galaxy.kv

Galaxy:
    BoxLayout:
        size: root.size

reference:

No comments:

Post a Comment