制作一款简易的调色画板,要用到的知识:页面布局、ToggleButton、ToggleButtonBehavior、get_color_from_hex(兼容十六进制编码颜色);功能上要可以选择颜色,选择画笔线宽,可以清除画板。具体实现如下:
选建一个main.py文件,内容代码如下
from kivy.app import App from kivy.graphics import Line,Color #引入绘图 from kivy.uix.widget import Widget #引入控件 from kivy.utils import get_color_from_hex #兼容十六进制颜色 from kivy.uix.behaviors import ToggleButtonBehavior #引入按钮开关行为 from kivy.uix.togglebutton import ToggleButton #引入开关按钮 class FrameToggleButton(ToggleButton): #当前按钮添加边框 def do_press(self): if self.state=='一般': ToggleButtonBehavior.do_press(self) class DrawCanvasWidget(Widget): #布局类 def __init__(self,**kwargs): super(DrawCanvasWidget, self).__init__(**kwargs) #设置默认颜色 self.change_color(get_color_from_hex('#19caad')) self.line_width=2 def on_touch_down(self, touch): #触摸显示轨迹 if Widget.on_touch_down(self,touch): return with self.canvas: touch.ud['current_line']=Line(points=(touch.x,touch.y),width=self.line_width) def on_touch_move(self, touch): #连线画线 if 'current_line' in touch.ud: touch.ud['current_line'].points+=(touch.x,touch.y) def change_color(self,new_color): #调色选择画笔颜色 self.last_color=new_color self.canvas.add(Color(*new_color)) def change_line_width(self,line_width='一般'): #选择画笔线宽 self.line_width={'较细':1,'一般':2,'较粗':4}[line_width] def clear_canvas(self): #清空画板 saved=self.children[:] self.clear_widgets() self.canvas.clear() for widget in saved: self.add_widget(widget) self.change_color(self.last_color) class PaintApp(App): #继承App类 #实现App类的build()方法(继承自App类) def build(self): self.canvas_widget=DrawCanvasWidget() return self.canvas_widget #返回根控件 if __name__=='__main__': PaintApp().run()