我试图用特定的面具掩盖图像,但我似乎无法找到方法。
我已阅读文档并发现此https://kivy.org/docs/api-kivy.graphics.stencil_instructions.html#看起来很有前途,但示例仅限于kivy语言(我不会在我的项目中使用)
我也发现了这个https://groups.google.com/forum/#!topic/kivy-users/-XXe3F2JoSc,但是第一个例子有点令人困惑,第二个例子使用的是StencilView,这似乎是另一回事
因此,一个普遍的例子会被认可
部分代码:
#some code...
picture_mask = Image(source = "Assets/picture_frame_mask.png", size_hint = (0, 0),
size = (200, 200),
pos = (50,100))
#Now what ?
player_picture = Image(source = "Assets/player.png", size_hint = (0, 0),
allow_stretch = True, keep_ratio = False,
size = (200, 200),
pos = (50,100))
self.add_widget(player_picture)
#rest of code...
答案 0 :(得分:0)
Tito已经在邮件列表中回答了它,但我会对它进行更多描述。要在画布中放置图像,您可以完全使用Rectangle()
,source
。但是这里有一个适当大小的问题,所以要么写出图像的完整大小,要么写size=[640/5.0,480/5.0]
或者只是640/5
(我使用py2.7)
如何使用Stencil在文档中描述,在python中它非常相似。您使用with canvas:
,其中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()