使用 Python 中的 Arcade 庫繪製橢圓


Python 是程式設計世界中最流行的語言之一。Python 語言提供的廣泛的庫和工具使其成為最常用的語言。談到庫,我們有 Arcade 庫,這是一個充當多媒體庫的 Python 庫,有助於建立 2D 遊戲和圖形,這些遊戲和圖形可以包含在其中。在本文中,我們將使用 Arcade 庫在 Python 中繪製橢圓。

什麼是 Arcade 庫?

Python 中的一個多媒體庫,它提供了各種用於建立 2D 遊戲、圖形物件、使用線條、圓形、矩形等形狀的功能。該庫能夠解決其建立的目的,即開發更逼真的圖形。

該庫提供了廣泛的功能,因為它構建在 Pyglet 之上,Pyglet 是一個多媒體庫,為開發人員提供了一個簡單的介面來建立新系列的遊戲和其他應用程式。由於該庫是內建庫,因此無需安裝它。您只需在需要時匯入它即可。匯入庫後,您可以訪問其中的函式。

為了繪製不同的形狀,Arcade 為每個形狀提供了不同的函式,例如

  • arcade.draw_circle_filled

  • arcade.draw_rectangle_filled

  • arcade.draw_polygon_filled

  • arcade.draw_line()

  • arcade.draw_point()

  • arcade.draw_triangle_filled()

  • arcade.draw_ellipse()

要使用 Arcade 庫繪製橢圓,您可以使用兩種不同的方法,即使用“arcade.draw_ellipse_filled”或“arcade.draw_ellipse_outline()”函式。我們將學習這兩個函式。

使用 arcade.draw_ellipse_filled() 方法

如果要繪製填充的橢圓,我們需要使用draw_ellipse_filled()方法。

示例

在此示例中,我們只是定義了螢幕的寬度和高度作為視窗的大小。

  • 然後我們使用 arcade.open_window() 函式開啟一個視窗。您可以使用“arcade.set_background_color(arcade.color.WHITE)”函式設定視窗的背景。

  • 最後,使用“arcade.draw_ellipse_filled(SCR_WIDTH/2, SCR_HEIGHT/2, 200, 100, arcade.color.ROYAL_BLUE)”函式繪製一個橢圓,其中傳遞了五個引數,這些引數定義了橢圓的特徵。

import arcade	
# defining screen dimensions 
SCR_WIDTH = 640
SCR_HEIGHT = 480
# create a window
arcade.open_window(SCR_WIDTH, SCR_HEIGHT, "Drawing an ellipse example")
arcade.set_background_color(arcade.color.WHITE)
# start rendering process
arcade.start_render()
# filled ellipse dimensions
arcade.draw_ellipse_filled(SCR_WIDTH/2, SCR_HEIGHT/2, 200, 100, arcade.color.ROYAL_BLUE)
arcade.finish_render()

arcade.run()

輸出

arcade.draw_ellipse_outline() 函式

此方法與前面一種方法相同,但唯一的區別在於我們提供六個引數時。在提供引數時,異常出現在邊框寬度中。

  • 這裡我們將橢圓的邊框寬度設定為 10。在使用此庫時,請確保為函式提供有效的引數,首先定義變數,否則可能會遇到諸如未定義變數錯誤之類的錯誤。

  • 還要檢查庫的版本是否未過時。您可以透過在命令提示符中傳遞命令“pip install—upgrade arcade”來從 Python 包管理器更新版本。

填充橢圓與輪廓橢圓相比,唯一的例外是邊框寬度。在填充橢圓的情況下不需要它。

示例

以下是一個示例 -

import arcade
# dimensions for the screen
SCR_WIDTH = 640
SCR_HEIGHT = 480
# open window for drawing the object
arcade.open_window(SCR_WIDTH, SCR_HEIGHT, "Drawing an ellipse outline example")
arcade.set_background_color(arcade.color.WHITE_SMOKE)
# start rendering process
arcade.start_render()
# Draw an outlined ellipse with a red color
arcade.draw_ellipse_outline(SCR_WIDTH/2, SCR_HEIGHT/2, 200, 100, arcade.color.RED, 10)

arcade.finish_render()
arcade.run()

輸出

結論

在本文中,我們從 Arcade 庫的基礎知識開始。我們回顧了基礎知識,包括 Arcade 庫中用於繪製各種形狀的函式以及庫的功能。為了繪製橢圓,我們使用了兩種不同的方法,每種形式都是為了不同的用途而繪製的。請正確遵循這些步驟並避免文章中解釋的錯誤。

更新於:2023 年 10 月 11 日

103 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告