#!/usr/bin/env python
#coding=utf-8
#-------------------------------------------------------------------------------
# 名 稱:簡單函數繪製類
# 版 本:V0.1
# 作 者:mapig (http://mapig.cnblogs.com QQ:33221979)
# 功 能:產生簡單函數映像
# 創 建:2009-05-18
# 備 註:需要 Python Imaging Library (PIL)
#-------------------------------------------------------------------------------
import math
import Image
import ImageDraw
class DrawFun():
#畫布像素尺寸
width = 512
height = 512
#X取值範圍
min = -10
max = 10
#X的步長值
step = 1
#X單位值像素
unit = 1
#畫板對象
canvas = None
#畫筆對象
draw = None
#畫布中心值位移值
ctrx = 0
ctry = 0
def __init__(self, width, height, min, max, step, unit):
self.width = width
self.height = height
self.min = min
self.max = max
self.step = step
self.unit = unit
#建立畫板對象
self.canvas = Image.new("RGB", [self.width, self.height],(255,255,255))
#建立畫筆對象
self.draw = ImageDraw.Draw(self.canvas)
#擷取畫布中心點
self.ctrx = math.floor(self.width/2)
self.ctry = math.floor(self.height/2)
#繪製中心軸線
self.draw.line([(0,self.ctry),(self.width,self.ctry)], fill =(0,0,0))
self.draw.line([(self.ctrx,0),(self.ctrx,self.height)], fill =(0,0,0))
#顯示儲存格數 左右對稱計算
viewx = int(math.floor((self.width/self.unit + 1)/2))
viewy = int(math.floor((self.height/self.unit + 1)/2))
#繪製儲存格
for x in range(1,viewx+1):
offsetx = x * self.unit
self.draw.line([(self.ctrx + offsetx,0),(self.ctrx + offsetx,self.height)], fill =(200,200,200))
self.draw.line([(self.ctrx - offsetx,0),(self.ctrx - offsetx,self.height)], fill =(200,200,200))
for y in range(1,viewy+1):
offsety = y * self.unit
self.draw.line([(0,self.ctry + offsety),(self.width,self.ctry + offsety)], fill =(200,200,200))
self.draw.line([(0,self.ctry - offsety),(self.width,self.ctry - offsety)], fill =(200,200,200))
def paint(self, fun, color):
#結果點集
aryPoint = []
#轉換為1為步長
min = int(math.floor(self.min/self.step))
max = int(math.floor(self.max/self.step))
for i in range(min, max):
#實際函數值
x = i * self.step
y = fun(x)
#笛卡爾座標繫到螢幕座標系
#比例變換
x = x * self.unit
y = y * self.unit
#座標變換
curX = self.ctrx + x
curY = self.ctry - y
#儲存座標到數組
aryPoint.append((curX,curY))
#繪製函數
self.draw.point(aryPoint,fill = color)
#顯示圖片
def show(self):
#顯示圖片
self.canvas.show()
#儲存到JPG
def saveToJPG(self, path):
self.canvas.save(path,"JPEG")
#儲存到PNG
def saveToPNG(self, path):
self.canvas.save(path,"PNG")
def sin(x):
return math.sin(x)
def cos(x):
return math.cos(x)
def tan(x):
return math.tan(x)
if __name__ == "__main__":
#DrawFun("畫布寬度","畫布高度","x最小值","x最大值","x步長值","x單位值像素大小")
drawfun = DrawFun(512, 512, -10, 10, 0.001, 50)
#DrawFun.paint(f(x)函數,RGB顏色)
drawfun.paint(sin,(255,0,0))
drawfun.paint(cos,(0,255,0))
drawfun.paint(tan,(0,0,255))
#顯示函數映像
drawfun.show()
#儲存到圖片
drawfun.saveToJPG("demo.jpg")
drawfun.saveToPNG("demo.png")
產生效果