from kivy.app import App
from kivy.graphics import Line, Color # 引入绘图线条,颜色
from kivy.uix.widget import Widget # 引入控件
from kivy.lang import Builder
from kivy.utils import get_color_from_hex
Builder.load_string("""
#:import C kivy.utils.get_color_from_hex
<DrawCanvasWidget>:
canvas.before:
# 最下面纸的颜色
Color:
rgba:[1,1,1,1]
# 形状
Rectangle:
# 位置
pos:self.pos
# 大小
size:self.size
Button:
background_color:C('#FF0000')
text:'1'
""")
# 布局类
class DrawCanvasWidget(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# 1.设置默认颜色,在画布中加入颜色 16进制写法 # 画笔的颜色
new_color = get_color_from_hex('#FF0000')
self.canvas.add(Color(*new_color))
# 1.设置默认颜色,在画布中加入颜色 十进制写法传入0到1的浮点数
# self.canvas.add(Color(rgb=[0,0,0]))
self.line_width = 1 # 线宽
# 触摸显示轨迹
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)
# 应用类
class PaintApp(App):
def build(self):
self.draw_canvas_widget = DrawCanvasWidget()
return self.draw_canvas_widget
if __name__ == '__main__':
PaintApp().run()