Pygame(四)畫橢圓,弧
前情提要:
作業答案
- 正方形與內切圓
def rect_circle():
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255,255,255))
# 畫正方形
rect = pygame.Rect(300, 200, 200, 200)
pygame.draw.rect(screen, (0, 0, 255), rect, width = 1)
# 畫內切圓, 半徑因爲正方形的線寬佔了一個,所以半徑要相應的少一個
pos = 400, 300
radius = 99
pygame.draw.circle(screen, (255, 0, 0), pos, radius, )
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
效果圖:
- 圓與內接正方形
def circle_rect():
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255,255,255))
# 畫外面的圓
pos = 400, 300
radius = 101
pygame.draw.circle(screen, (255, 0, 0), pos, radius, )
# 畫內接正方形
width = height = 100*1.41 # 計算內接正方形的寬高
left, top = 400 - width/2, 300-height/2 # 計算內接正方形的左上角座標
rect = pygame.Rect(left, top, width, height)
pygame.draw.rect(screen, (0, 0, 255), rect)
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
效果圖:
本節提要
內容詳情
畫橢圓
pygame.draw.ellipse(Surface, color, rect, width)
參數說明
Surface: Surface對象
color: 線條顏色
rect:橢圓的外切矩形
width: 線粗(width=0 是實心橢圓)
備註:
當矩形是一個正方形的時候,畫出來的橢圓其實是一個圓_.
示例代碼:
# 畫橢圓
def draw_ellipse():
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255, 255, 255))
# 畫橢圓
rect = (100,100,200,100)
pygame.draw.ellipse(screen, (0,255,255), rect, 1)
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
效果圖:
說明一下:
這裏的橢圓是用矩形框起來的.是矩形的內切橢圓.因此,在實際使用的時候,要根據橢圓的中心位置以及橢圓的寬度與高度來計算具體的參數值
讀者可以自行將其轉化公式寫一下,體會一下.
畫弧
pygame.draw.arc(Surface,color, rect, start_angle, end_angle, width)
參數說明:
Surface: Surface對象
color: 線條顏色
rect:弧所在的圓(橢圓)的外切矩形
width: 線粗(width=0時看不見)
start_angle:起始角度
end_angle:終止角度
備註:角度的問題
- 角度以中心爲起點,向右方向爲0度(3點角度爲0,逆時針方向爲正, 12點爲90度,9點爲180度, 6點爲270度
- 角度是弧度製表示的.pi = 180度, pi/2 = 90度.
- pi這個常數來自math庫
- 當角度超過360度時
- 角度取負值時,順時針方向旋轉計算.
- 弧的選取一定是從起點到終點逆時針方向截取.
####示例代碼
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255, 255, 255))
# 畫橢圓
rect = (100,100,200,100)
pygame.draw.arc(screen, (0,255,255), rect, 1.5, -1, width=1)
rect = (300, 100, 100, 100)
pygame.draw.arc(screen, (0,0,255), rect, 0, pi/2*3, width=2)
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
效果圖:
作業:
畫出如下圖形: