โค้ดจากไฟล์ .py
from kivy.app import App
from kivy.uix.relativelayout import RelativeLayout
class DrawingSpace(RelativeLayout):
pass
class DrawingApp(App):
def build(self):
return DrawingSpace()
DrawingApp().run()
โค้ดจากไฟล์ .kv
<DrawingSpace>:
canvas:
Rectangle:
pos: self.x+10,self.top-80
size:self.width*0.15,self.height*0.3
Ellipse:
angle_start: 120
angle_end: 400
pos: 150, root.top-80
size: 80, 80
และจากตัวอย่างโค้ดด้านบนนั้นจะทำให้เราได้ผลลัพธ์ที่แสดงออกมาคือ
โดยจะมีอีก 2 เรื่องที่เหลือคือการใส่สีลงไปบนรูปและการหมุนรูปโดยไม่จำเป็นต้องไปโฟกัสเท่าไหร่มาต่อกันที่การวาดตัว stickman ในคราวนี้จะให้มันทำการเพิ่มตัว stickman เข้าไปจากตัวอย่างท้ายบทที่ 1 โดยเริ่มจากการเพิ่มไฟล์เข้าไปตัวนึงคือ comicwidgets.kv โดยจะต้องใช้คำสั่ง builder เพิ่มเข้าไปอีก 1 บรรทัดในไฟล์ comiccreator.py โดยให้โค้ดมาดังนี้
โค้ดในไฟล์ comicwidgets.kv
<StickMan@RelativeLayout>:
size_hint: None,None
size:48, 48
canvas:
PushMatrix
Line:
circle: 24,38,5
Line:
points: 24,33,24,15
Line:
points: 14,5,24,15
Line:
points: 34,5,24,15
Translate:
y: 48-8
Rotate:
angle: 180
axis: 1,0,0
Line:
points: 14,5,24,15
Line:
points: 34,5,24,15
PopMatrix
โดยจะเห็นว่ามีคำสั่ง PushMatrix คือคำสั่งที่ใช้เก็บค่าก่อนที่จะเปลี่ยนแปลงทั้งหมดไว้และใช้คำสั่ง PopMatrix คือการคืนค่าที่เก็บไว้คืนมายังไม่หมดเราต้องทำการแก้ไฟล์ toolbox.kv และ drawingspace.kv เพิ่มอีกด้วย
โค้ดในไฟล์ toolbox.kv
<ToolButton@ToggleButton>:
size_hint: None,None
size: 48,48
group: 'tool'
canvas:
PushMatrix:
Translate:
xy: self.x,self.y
canvas.after:
PopMatrix:
<ToolBox@GridLayout>:
cols: 2
padding: 2
ToolButton:
canvas:
Line:
circle: 24,24,14
ToolButton:
canvas:
Line:
points: 10,10,38,38
ToolButton:
StickMan:
pos_hint: {'center_x' : .5, 'center_y' : .5}
โค้ดในไฟล์ drawingspace.kv
<DrawingSpace@RelativeLayout>:
Label:
markup: True
StickMan:
pos_hint: {'center_x': .5, 'center_y':.5}
canvas.before:
Translate:
xy:-self.width/2 , -self.height/2
Scale:
xyz: 2, 2, 0
StickMan:
และหลังจากเราทำการแก้โค้ดทั้งหมดเราก็จะได้ผลลัพท์แสดงหน้าจอใหม่คือ


ไม่มีความคิดเห็น:
แสดงความคิดเห็น