如果图像不是窗口的大小,是否可以将图像扩展为覆盖整个窗口并裁剪自身以适应而不丢失其比例?
答案 0 :(得分:0)
如果您真的想拉伸和裁剪Image
,则可以使用StencilView
进行裁剪。这是一个可能的实现:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.stencilview import StencilView
class MyStencilView(FloatLayout, StencilView):
def on_size(self, *args):
self.children[0].adjust_image_size(self)
class MyImage(Image):
def adjust_image_size(self, stencil):
stencil_ratio = stencil.width / float(stencil.height)
if self.image_ratio > stencil_ratio:
self.width = stencil.height * self.image_ratio
self.height = stencil.height
else:
self.width = stencil.width
self.height = stencil.width / self.image_ratio
theRoot = Builder.load_string('''
FloatLayout:
MyStencilView:
MyImage:
size_hint: None, None
pos_hint: {'center_x':0.5, 'center_y':0.5}
keep_ratio: True
allow_stretch: True
source: '/path/to/some/image'
''')
class TestApp(App):
def build(self):
return theRoot
TestApp().run()
想法是MyImage
小部件的大小已根据需要进行调整,以允许MyStencilView
进行裁剪。 FloatLayout
的{{1}}基可以使用MyStencilView
,在这种情况下,可以确保裁切以图像为中心。