【Kivy】实战--画板(九)

只是个人学习的时候的一些笔记,如果有什么错误的地方还请各位勿喷,手下留情,期待您的指正。 定期会更新文章到www.sea-whales.cn我的个人网站中,有兴趣的小伙伴可以进来看看

实战–画板

我们先来做一个初始画板,先不添加其他复杂元素,来实现能写字的功能:

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color


class DrawCanvasWidget(Widget):
    def __init__(self, **kwargs):
        super(DrawCanvasWidget, self).__init__(**kwargs)
        """设置画笔的默认颜色为黑色"""
        self.canvas.add(Color(rgb=[0, 0, 0]))
        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)


class PaintApp(App):
    def build(self):
        self.draw_canvas_widget = DrawCanvasWidget()
        return self.draw_canvas_widget


if __name__ == '__main__':
    PaintApp().run()

Kivy提供了on_touch_downon_touch_move方法来实现监听屏幕点击和屏幕移动触发事件

<DrawCanvasWidget>:
    canvas.before:
        Color:
            rgba:[1,1,1,1]
        Rectangle:
            pos: self.pos
            size: self.size

以上能够实现使用一种黑色画笔在白色画板上进行写字。接下来,我们试试能否通过选择颜色去替换画笔颜色,然后进行绘画。
Kivy种设置颜色的方法一般是使用rgba(r红色,g绿色,b蓝色,alpha名度)一般我们就是使用颜色和255进行比值,得到百分比。我们也可以直接使用十六进制进行表示。当需要大量颜色的时候,Kivy在utils包内也提供了 get_color_from_hex()方法进行16进制和百分比转换,我们使用当时时候传入十六进制字符串即可。
我们可以选择在python内使用,还是在kv文件内使用,使用方法如下:
python文件内:

from kivy.utils import get_color_from_hex
get_color_from_hex('#98feab')

kv文件内使用:

#:import C kivy.utils.get_color_from_hex
Button:
    background_color: C('#98feab')

我们可以在画板类里面写上一个方法来改变canvas画布颜色的方法。不是canvas.before背景:

def chang_color(self, new_color):
    """调色"""
    self.canvas.add(Color(*new_color))

通过chang_color方法在init中初始化一个颜色。在kv文件设置按钮,通过按钮单击调用chang_color激活颜色的改变。
具体代码如下:

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color
from kivy.utils import get_color_from_hex


class DrawCanvasWidget(Widget):
    def __init__(self, **kwargs):
        super(DrawCanvasWidget, self).__init__(**kwargs)
        """设置画笔的默认颜色为黑色"""
        self.change_color(get_color_from_hex('#12aced'))
        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.canvas.add(Color(*new_color))


class PaintApp(App):
    def build(self):
        self.draw_canvas_widget = DrawCanvasWidget()
        return self.draw_canvas_widget


if __name__ == '__main__':
    PaintApp().run()

kv文件

#:import C kivy.utils.get_color_from_hex   # 引入颜色转换方法

<BottomColorButton@ToggleButton>:
    group: 'color'
    background_normal: ''
    background_down: ''
    border: (3, 3, 3, 3)
    on_release: app.draw_canvas_widget.change_color(self.background_color)


<DrawCanvasWidget>:
    canvas.before:
        Color:
            rgba: [1, 1, 1, 1]
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        id: bottom_box
        orientation: 'horizontal'
        padding: 2
        spacing: 2
        size: root.width, 40

        BottomColorButton:
            background_color: C('#19caad')
            state: 'down'                     # 按钮状态

        BottomColorButton:
            background_color: C('#8cc7b5')

        BottomColorButton:
            background_color: C('#a0eee1')

        BottomColorButton:
            background_color: C('#bee7e9')

        BottomColorButton:
            background_color: C('#beedc7')

        BottomColorButton:
            background_color: C('#d6d5b7')

        BottomColorButton:
            background_color: C('#d1ba74')

        BottomColorButton:
            background_color: C('#e6ceac')

        BottomColorButton:
            background_color: C('#ecad9e')

        BottomColorButton:
            background_color: C('#f4606c')

        BottomColorButton:
            background_color: C('#3498db')

        BottomColorButton:
            background_color: C('#1abc9c')

        BottomColorButton:
            background_color: C('#2ecc71')

        BottomColorButton:
            background_color: C('#f1c40f')

        BottomColorButton:
            background_color: C('#e67e22')

        BottomColorButton:
            background_color: C('#e74c3c')

        BottomColorButton:
            background_color: C('#9b59bc')

        BottomColorButton:
            background_color: C('#ecf0f1')

        BottomColorButton:
            background_color: C('#95a5a6')

        BottomColorButton:
            background_color: C('#000000')

有了画笔颜色的改变,我们接下来看看改变画笔的粗细。
同理,使用与改变颜色相同方法做一个画笔粗细:

    def change_line_width(self, line_width='Normal'):
        self.line_width = {'Thin': 1, 'Normal': 2, 'Thick': 4}[line_width]
<LineWidthButton@ToggleButton>:
    group: 'line_width'
    color: C('#2c3e50')
    background_color: C('#ecf0f1')
    background_normal: ''
    background_down: ''
    border: (3, 3, 3, 3)
    on_release: app.draw_canvas_widget.change_line_width(self.text)

画布内新增改变按钮


    BoxLayout:
        orientation: 'horizontal'
        padding: 2
        spacing: 2
        x: 0
        top: root.top
        size_hint: None,None
        size: 280, 44

        LineWidthButton:
            text: 'Thin'

        LineWidthButton:
            text: 'Normal'
            state: 'down'

        LineWidthButton:
            text: 'Thick'

新增清空画板功能;

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color
from kivy.utils import get_color_from_hex
# 添加边框样式
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.uix.togglebutton import ToggleButton


# 因为已经在这边添加了ToggleButton的公共类,提取出公共属性的两个就不需要使用ToggleButton而是可以直接使用
# FrameToggleButton即可
class FrameToggleButton(ToggleButton):
    """当前按钮添加边框"""

    def do_press(self):
        """点击改变状态"""
        if self.state == 'normal':
            ToggleButtonBehavior.do_press(self)


class DrawCanvasWidget(Widget):
    def __init__(self, **kwargs):
        super(DrawCanvasWidget, self).__init__(**kwargs)
        """设置画笔的默认颜色为黑色"""
        self.change_color(get_color_from_hex('#12aced'))
        self.change_line_width()

    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='Normal'):
        self.line_width = {'Thin': 1, 'Normal': 2, 'Thick': 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):
    def build(self):
        self.draw_canvas_widget = DrawCanvasWidget()
        return self.draw_canvas_widget


if __name__ == '__main__':
    PaintApp().run()


#:import C kivy.utils.get_color_from_hex

<BottomColorButton@FrameToggleButton>:
    group: 'color'
    background_normal: ''
    background_down: ''
    border: (1, 1, 1, 1)
    on_release: app.draw_canvas_widget.change_color(self.background_color)

<LineWidthButton@FrameToggleButton>:
    group: 'line_width'
    color: C('#2c3e50')
    background_color: C('#ecf0f1')
    background_normal: ''
    background_down: ''
    border: (3, 3, 3, 3)
    on_release: app.draw_canvas_widget.change_line_width(self.text)


<DrawCanvasWidget>:
    canvas.before:
        Color:
            rgba: [1, 1, 1, 1]
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        orientation: 'horizontal'
        padding: 2
        spacing: 2
        x: 0
        top: root.top
        size_hint: None,None
        size: 280, 44

        LineWidthButton:
            text: 'Thin'

        LineWidthButton:
            text: 'Normal'
            state: 'down'

        LineWidthButton:
            text: 'Thick'

        Button:
            text: 'Clear'
            on_release: root.clear_canvas()


    BoxLayout:
        id: bottom_box
        orientation: 'horizontal'
        padding: 2
        spacing: 2
        size: root.width, 40

        BottomColorButton:
            background_color: C('#19caad')
            state: 'down'

        BottomColorButton:
            background_color: C('#8cc7b5')

        BottomColorButton:
            background_color: C('#a0eee1')

        BottomColorButton:
            background_color: C('#bee7e9')

        BottomColorButton:
            background_color: C('#beedc7')

        BottomColorButton:
            background_color: C('#d6d5b7')

        BottomColorButton:
            background_color: C('#d1ba74')

        BottomColorButton:
            background_color: C('#e6ceac')

        BottomColorButton:
            background_color: C('#ecad9e')

        BottomColorButton:
            background_color: C('#f4606c')

        BottomColorButton:
            background_color: C('#3498db')

        BottomColorButton:
            background_color: C('#1abc9c')

        BottomColorButton:
            background_color: C('#2ecc71')

        BottomColorButton:
            background_color: C('#f1c40f')

        BottomColorButton:
            background_color: C('#e67e22')

        BottomColorButton:
            background_color: C('#e74c3c')

        BottomColorButton:
            background_color: C('#9b59bc')

        BottomColorButton:
            background_color: C('#ecf0f1')

        BottomColorButton:
            background_color: C('#95a5a6')

        BottomColorButton:
            background_color: C('#000000')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sea-Whales

感谢希望文章对您有用!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值