Skip to content

Instantly share code, notes, and snippets.

@tito
Created November 8, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tito/1cc7c7b7aff153c8eb0252fff06b61ac to your computer and use it in GitHub Desktop.
Save tito/1cc7c7b7aff153c8eb0252fff06b61ac to your computer and use it in GitHub Desktop.
Image scatter that collide on white color of (can be changed for opaque)
from kivy.lang import Builder
from kivy.factory import Factory as F
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty
from kivy.core.image import Image as CoreImage
Builder.load_string("""
<ImgScatter>:
size_hint: None, None
canvas:
Color:
rgba: 1, 1, 1, 1
Rectangle:
size: self.size
texture: self.texture
""")
class ImgScatter(F.Scatter):
source = StringProperty()
texture = ObjectProperty(None, allownone=True)
is_touch_down_collide = BooleanProperty(False)
def on_source(self, *largs):
self.img = img = CoreImage(self.source, keep_data=True)
self.texture = img.texture
self.size = img.texture.size
self.is_touch_down_collide = False
def collide_point(self, x, y):
if not self.is_touch_down_collide:
# default collide_point
return super(ImgScatter, self).collide_point(x, y)
lx, ly = self.to_local(x, y)
if lx < 0 or lx > self.width:
return False
if ly < 0 or ly > self.height:
return False
lx /= float(self.width)
ly /= float(self.height)
cx = int(lx * self.texture.size[0])
cy = int((1 - ly) * self.texture.size[1])
color = self.img.read_pixel(cx, cy)
# test alpha ?
# return color[-1] > 0
return color == [1, 1, 1, 1]
def on_touch_down(self, touch):
try:
self.is_touch_down_collide = True
return super(ImgScatter, self).on_touch_down(touch)
finally:
self.is_touch_down_collide = False
if __name__ == "__main__":
from kivy.app import App
import sys
assert(len(sys.argv[1:]) >= 1)
class TestImgScatter(App):
def build(self):
self.root = F.FloatLayout()
for source in sys.argv[1:]:
self.root.add_widget(
ImgScatter(source=source)
)
TestImgScatter().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment