《Go语言入门到进阶实战》学习笔记:输出正弦函数(Sin)图像

1、设置图片背景色

    //设置图片大小
	const size=300
	//根据给定大小创建灰度图
	pic:=image.NewGray(image.Rect(0,0,size,size))
	//遍历每个像素
	for x:=0;x<size;x++{
		for y:=0;y<size;y++{
			pic.SetGray(x,y,color.Gray{255})
		}
	}

2、绘制正弦函数轨迹

    //从0到最大像素生成x坐标
	for x:=0;x<size;x++{
		s:=float64(x)*2*math.Pi/size
		//sin的幅度为一半的像素。向下偏移一半像素并翻转
		y:=size/2-math.Sin(s)*size/2
		pic.SetGray(x,int(y),color.Gray{0})
	}

3、写入图片文件

    //创建文件
	file,err:=os.Create("sin.png")
	if err!=nil{
		log.Fatal(err)
	}
	//使用PNG格式将数据写入文件
	png.Encode(file,pic)
	//将image信息写入文件中
	//关闭文件
	file.Close()

结果图

猜你喜欢

转载自blog.csdn.net/qq_36214481/article/details/88719070