边学边做Manim中创建正多边形

很多时候,在Manim中,我们需要创建一个多边形,其实我们可以使用Manim创建很多的几何图形,RegularPolygon 是用于创建正多边形的几何对象,属于 VMobject 类。以下是关键信息整合。

1.基本用法

RegularPolygon 通过指定边数 n 和圆半径 radius 创建正多边形,最重要的参数就是变数 n。例如:

1
2
3
4
5
6
7
from manim import *

class Example(Scene):
def construct(self):
pentagon = RegularPolygon(n=5, radius=2)
self.play(Create(pentagon))
self.wait(2)

上面的代码,就是利用RegularPolygon创建一个正五边形,radius是正五边形外接圆的半径。来看下面的视频

2.属性与扩展

  1. 颜色与填充 :支持 color(边颜色)和 fill_color(填充颜色),以及 fill_opacity(填充透明度)参数。
  2. 变换 :可通过 scale 方法调整大小,例如 polygon.scale(2) 将边长放大2倍3
  3. 子对象切割 :结合 Cutout 对象可创建空心多边形,例如从正方形中切割出多个小形状。

3.应用场景

常用于数学教学、图形演示等场景,例如展示几何变换、组合图形或动态效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
from manim import *

class RegularPolygonDemo(Scene):
def construct(self):
# 创建正五边形
pentagon = RegularPolygon(n=5, radius=2, color=RED, fill_opacity=1)
self.play(Create(pentagon))
self.wait(2)

# 创建缩放版本并移动到下方
scaled_pentagon = pentagon.copy().scale(1.5)
self.play(Transform(pentagon, scaled_pentagon))
self.wait(2)

来看演示的视频

以上代码展示了创建、缩放正多边形的基本操作,适用于教学或动画制作需求。

4.多边形变化变数

我们再来看一段代码,主要是利用 Python 的循环语句,来构造变数不断变化的正多边形,然后最终变成一个圆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from manim import *

class SmoothPolygonTransition(Scene):
def construct(self):
# 初始多边形
polygon = RegularPolygon(n=3, color=BLUE)
self.add(polygon)

# 逐步增加边数
for n_sides in [4, 5, 6, 8, 10, 12, 20, 50]:
new_polygon = RegularPolygon(
n=n_sides,
color=interpolate_color(BLUE, RED, (n_sides-3)/47),
fill_opacity=0.3
)
self.play(Transform(polygon, new_polygon))
self.wait(0.2)

# 最后变成圆形
circle = Circle(color=GREEN, fill_opacity=0.3)
circle.scale_to_fit_height(polygon.get_height())
self.play(Transform(polygon, circle))
self.wait()

来看视频效果

5.多边形的内切圆

对于圆来说,有一个外接多边形,有一个内接多边形,我们可以使用下面的代码,做出多边形的内切圆和外接圆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class CombinedShapes(Scene):
def construct(self):
polygon = RegularPolygon(n=8, color=BLUE, fill_opacity=0.3)
circle = Circle(radius=polygon.get_circumradius(), color=RED)

# 显示外接圆
self.add(polygon, circle)

# 显示内切圆
incircle = Circle(
radius=polygon.get_inradius(),
color=GREEN
)
self.add(incircle)

来看演示的效果

6.设定边长的多边形

我们还可以提前设定正多边形的边长,来绘制正多边形,甚至正多边形的内切圆和外接圆,来看代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from manim import *
import numpy as np

class PolygonWithCirclesChange(Scene):
def construct(self):
# 设置想要的边长
side_length = 2
# 计算对应的外接圆半径
# 公式: side_length = 2 * R * sin(π/n)
n = 5 # 五边形
R = side_length / (2 * np.sin(PI / n))
# 创建正多边形
polygon = RegularPolygon(n=n, radius=R, color=BLUE, fill_opacity=0.3)

# 使用正确的方法获取半径
circumradius = R # 外接圆半径(方法调用)
inradius = side_length / (2 * np.tan(PI / n)) # 内切圆半径(方法调用)

# 创建圆
circumcircle = Circle(radius=circumradius, color=RED)
incircle = Circle(radius=inradius, color=GREEN)

self.play(Create(polygon))
self.wait()
self.play(Create(circumcircle))
self.wait()
self.play(Create(incircle))
self.wait()

来看实际的效果代码

好了,今天的学习先到这里,后续会对这篇文章做出补充性说明。