我编写了以下代码,试图制作一个无缝流动的图像,该图像处于无限滚动状态。 (也许“无限滚动”这个词在这种情况下会产生误导,但它应该是无缝滚动,当图像的某个部分从底部消失时,它应该在消失后立即出现在顶部,这就是无缝滚动)
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock
class ScrollingImageApp(App):
def build(self):
self.root = BoxLayout(orientation='vertical')
# Create a non-interfering layer for scrolling image
self.scroll_layer = Image(source='pexels-tessa-k-896673.jpg', allow_stretch=True, keep_ratio=False)
self.root.add_widget(self.scroll_layer)
# Schedule the scroll function to be called every frame
Clock.schedule_interval(self.scroll_image, 1 / 60.0)
return self.root
def scroll_image(self, dt):
# Scroll the image vertically
self.scroll_layer.y -= 1
if self.scroll_layer.y < -self.scroll_layer.height:
self.scroll_layer.y = self.root.height
if __name__ == '__main__':
ScrollingImageApp().run()
# Image source: https://www.pexels.com/photo/timelapse-photo-of-gray-clouds-896673/
# The above image was made seamless using Gimp software (photoshop alternative)
有一些问题。
{我以为我可以使用同一图像的 2 个图像实例,然后在第一个图像消失时重置它,但我也无法实现任何代码。但老实说,我知道我们不需要 2 个图像来实现无缝滚动效果,而只需要一个应该连续滚动的实例。} 如何实现无缝滚动?
{问题是,如果我突然调整它的大小,图像的整个滚动会被重置,并再次从头开始,这是不应该发生的。}
如何解决这个问题?
请帮助我解决这两个问题?您认为有办法修复它们,以便无缝(/无限)滚动与适合宽度而不是高度的图片一起发生吗?
您可以使用两个
Image
对象来完成类似的操作。以下是使用此方法对 App
类的修改:
class ScrollingImageApp(App):
def build(self):
self.root = BoxLayout(orientation='vertical')
# Add a FloatLayout to contain the scrolling Images
fl = FloatLayout()
self.upper_image = Image(source='pexels-tessa-k-896673.jpg', allow_stretch=True, keep_ratio=False)
self.scroll_layer = Image(source='pexels-tessa-k-896673.jpg', allow_stretch=True, keep_ratio=False)
fl.add_widget(self.upper_image)
fl.add_widget(self.scroll_layer)
self.root.add_widget(fl)
# # Schedule the scroll function to be called every frame
Clock.schedule_interval(self.scroll_image, 1 / 60.0)
return self.root
def scroll_image(self, dt):
# Scroll the image vertically
self.scroll_layer.y -= 1
if self.scroll_layer.y < -self.scroll_layer.height:
self.scroll_layer.y = 0 # reset to starting position
# adjust the position of the upper Image
self.upper_image.y = self.scroll_layer.y + self.scroll_layer.height
请注意,当下方图像滚出屏幕时,
scroll_image()
方法会将 y
值 scroll_layer
(下方图像)重置为 0
。它还将上图像定位在下图像的正上方。