本文主要是介绍python与分形0012 - 【教程】旋转的彩色N边形(圆盘),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天周五,513330又不能666了,哎,腿都蹲麻了。
在上一节的教程中,我们讲了怎么通过三角形画一个多边形的方法。
今天,我们先来给它弄点色彩,再让它动起来,先来看看效果:
注:gif动图上传有1M限制,这个图被压缩了91.83%,原图更酷炫,看文末视频。
开始吧。
第一步,涂色
前面我们讲到多边形是用三角形拼接而成的,今天我们新引进两个函数,用来对封闭区域涂色。
turtle.begin_fill()
To be called just before drawing a shape to be filled.
turtle.end_fill()
Fill the shape drawn after the last call to begin_fill().
效果如下:
代码:
length = 400
turtle.color("white")turtle.goto(0, 0)
turtle.begin_fill()
turtle.pendown()
turtle.seth(0)
turtle.fd(length)
(x,y)=turtle.pos()
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.seth(72)
turtle.fd(length)
turtle.goto(x,y)
turtle.penup()turtle.end_fill()
第二步,更多涂色
然后,我们再来画多边形,给每个三角形不同的颜色。
我们用到的库是:colorsys
。
The colorsys module defines bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) color space used in computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1.
我们使用其中的函数:
colorsys.hsv_to_rgb(h, s, v)
Convert the color from HSV coordinates to RGB coordinates.
问:为什么用这个hsv转rgb?
答:HSV分别是色调、饱和度和亮度,其中H代表颜色信息。
如果把S和V固定,那么调整H就可以调整颜色,比较简单。
H,S,V ∈ [0, 1]
代码变一下:
def draw_gon(length, start_angle, line):angle = 360//linefor index in range(line):(r,g,b) = colorsys.hsv_to_rgb(index/line,1,1)turtle.color((r,g,b))turtle.goto(0, 0)turtle.begin_fill() turtle.pendown()turtle.seth(start_angle + angle*index)turtle.fd(length)(x,y)=turtle.pos()turtle.penup()turtle.goto(0, 0)turtle.pendown()turtle.seth(start_angle+angle*(index+1))turtle.fd(length)turtle.goto(x,y)turtle.penup()turtle.end_fill()
彩色五边形示例:
第三步,动起来
参考第一个教程中,让直线旋转起来的方式,让它动起来。
每次刷新的时候,我们改变多边形的角度。
最简单的代码:
for angle in range(360):turtle.clear()draw_gon(400, angle, 60)turtle.update()time.sleep(0.05)
ontimer版本:
angle=1
length=400def movie_gon():global angleturtle.clear()draw_gon(length, angle, 60)angle += 1if angle > 360:angle = 0turtle.ontimer(movie_gon, 0)movie_gon()
--EOF--
例行求粉,谢谢!
这篇关于python与分形0012 - 【教程】旋转的彩色N边形(圆盘)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!