0
0

More than 3 years have passed since last update.

KivyでSFライクなボタンを作る

Posted at

完成したもの

Kivyで画像などを使わずにSFっぽいボタン作れないかなと思って作った。
結果こんな感じのボタンができました。
SFButton.JPG

というわけで作ってみた

方針は単純で、ボタンのキャンバスに枠を二つ作ることで実現します。
main.pyとtest.kvを同階層において実行すれば最初の画像のようになります。

main.py
from kivy.app import App
from kivy.factory import Factory

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)

    def build(self):
        self.root = root = Factory.FloatLayout()

        btn = Factory.SFButton(
            text="This is SF !",
            size_hint=(0.5, 0.2),
            pos_hint={'x':0.25, 'y':0.4},
            on_release=self.btn_pushed
        )
        root.add_widget(btn)

        return root

    def btn_pushed(self, instance, *args):
        print(f"{instance.text} pushed !")


def main():
    TestApp().run()

if __name__ == '__main__':
    main()
test.kv
#: import hex kivy.utils.get_color_from_hex

<SFButton@Button>:
    background_color: hex('#44acac')
    canvas.before:
        Color:
            rgba: hex('#26c7e5')
        Line:
            width: 2
            rectangle: self.x, self.y, self.width, self.height

        Color:
            rgba: hex('#26c7e5')
        Line:
            width: 1
            rectangle: self.x-4, self.y-4, self.width+8, self.height+8

ポイント

canvas.beforeでは色を指定→図を指定を連続すると絵が描けるそうですね。
それを利用して内側→外側の順に四角形を描画しています。
ここで外側の線を引くとき、内側と同じように

rectangle: self.x, self.y, self.width, self.height

としてしまうと・・・
failed.JPG
とこのように内側の線しか見えなくなります。(なんで外側の線で上書きされないの??)
その為外側の線では

rectangle: self.x-4, self.y-4, self.width+8, self.height+8

と少し大きな四角形になるように調整しました。この辺は外側の線のwidthをでまた変わると思います。ちなみに

rectangle: self.x-3, self.y-3, self.width+6, self.height+6

の場合は
ex2.JPG
となりました。その他いろいろ試しましたが個人的には冒頭の画像になるtest.kvの調整が好きです。

色の指定は16進数の方が見やすいかと思い、kivy.utils.get_color_from_hex関数を利用しています。

最後に

画像なしでもまぁっぽい感じが出せたとは思います。
最終的には押されたときもSFライクなデザインで動作させたいなぁ、、

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0