鐵托已經在郵件列表中回答了它,但我會多描述一下。要在畫布內部放置圖像,您可以準確使用Rectangle()
,source
。但在這裏配備了一個適當大小的問題,所以無論是寫入圖像的完整大小,或像size=[640/5.0,480/5.0]
或者只是640/5
(我用py2.7)
如何使用模板文檔中描述的那樣,在Python它非常相似。您使用with canvas:
,其中畫布是您小部件的畫布,因此self.canvas
。對你而言有趣的是mask()
功能,我在這裏評論了幾件事情,以便讓你清楚。
要理解面具實際做了什麼,可以將面具想象成一張帶有洞的紙。你只能看到洞裏有什麼。
from kivy.graphics import *
#^^^^^^ all imports you need for that to work + App()/runTouchApp()
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class Root(Widget):
def __init__(self, **kw):
super(Root, self).__init__()
with self.canvas:
Color(1,0,0,0.5)
Rectangle(pos=self.pos, size=Window.size)
bx=BoxLayout(width=Window.width)
but1=Button(text="mask it!")
but1.bind(on_release=self.mask)
but2=Button(text="clear it!")
but2.bind(on_release=self.clear)
bx.add_widget(but1)
bx.add_widget(but2)
self.add_widget(bx)
#after few hundred lines of code you'll hate to type even ".add_"
#binding on_release and other is a way more shorter
#learn kv, have less troubles :)
def mask(self, *args):
with self.canvas:
#you have to "push" the stencil instructions
#imagine StencilPush and StencilPop as { and }
StencilPush()
#set mask
Rectangle(pos=[self.pos[0],self.pos[1]+200], size=[100,100])
#use mask
StencilUse()
#draw something and mask will be placed on it
#Color(1,1,1) for full color, otherwise it tints image
Color(0,1,0)
Rectangle(source='<your picture>',\
pos=[0,0], size=[Window.width-200,Window.height-200])
#disable Stencil or mask will take effect on everything
#until StencilPop()
StencilPop()
#here it doesn't take effect
Color(0,1,1)
Rectangle(pos=[self.pos[0]+200,self.pos[1]+200],\
size=[Window.width-200,Window.height-200])
#However here, when StencilPop() and StencilUse()
#are again, mask is still in the memory
StencilPush()
StencilUse()
#mask is applied... and draws nothing
#because it's not in the mask's area
Color(1,1,0)
Rectangle(pos=[self.pos[0]+200,self.pos[1]+200],\
size=[Window.width-200,Window.height-200])
#I think UnUse() is optional
StencilUnUse()
#and of course Pop() it
StencilPop()
def clear(self, *args):
self.canvas.clear()
self.__init__()
class My(App):
def build(self):
return Root()
My().run()
您對kv示例有什麼不瞭解?你有沒有試過把它轉換成python代碼? – inclement
我是一般的編程新手,所以有些事情對我來說並不像他們應該那樣明顯。所以我嘗試了,但我不知道如何在Python代碼中使用StencilPush,例如 – Xellon
值得學習kv lang,因爲它不難並且極大地簡化了一個項目。而簡化的東西就是最喜歡的新手。 – jligeza