2012-11-14 202 views
0

我有一堆图像(说10)我已经生成为数组或PIL对象。蟒蛇排列在画布上的图像在一个圆圈

我需要将它们集成到一个循环的方式来显示它们,它应该调整自己的屏幕分辨率,是否有什么可以做到这一点的Python?

我已经尝试使用粘贴,但搞清楚的决议画布和位置粘贴是痛苦的,想知道是否有一个更简单的解决方案?

回答

5

可以说,当相邻点之间存在恒定角度theta时,点均匀排列成一个圆。 theta可以计算为2 * pi弧度除以点数。第一点是在角度0相对于x轴,在角度theta*1,在角度theta*2第三点的第二点等

使用简单的三角学,可以找到X和任意点的Y坐标即位于一个圆的边缘。在角度ohm点躺在圆半径r

 
xFromCenter = r*cos(ohm) 
yFromCenter = r*sin(ohm) 

使用这种数学,有可能在一个圆上均匀排列你的图像:

import math 
from PIL import Image 

def arrangeImagesInCircle(masterImage, imagesToArrange): 
    imgWidth, imgHeight = masterImage.size 

    #we want the circle to be as large as possible. 
    #but the circle shouldn't extend all the way to the edge of the image. 
    #If we do that, then when we paste images onto the circle, those images will partially fall over the edge. 
    #so we reduce the diameter of the circle by the width/height of the widest/tallest image. 
    diameter = min(
     imgWidth - max(img.size[0] for img in imagesToArrange), 
     imgHeight - max(img.size[1] for img in imagesToArrange) 
    ) 
    radius = diameter/2 

    circleCenterX = imgWidth/2 
    circleCenterY = imgHeight/2 
    theta = 2*math.pi/len(imagesToArrange) 
    for i, curImg in enumerate(imagesToArrange): 
     angle = i * theta 
     dx = int(radius * math.cos(angle)) 
     dy = int(radius * math.sin(angle)) 

     #dx and dy give the coordinates of where the center of our images would go. 
     #so we must subtract half the height/width of the image to find where their top-left corners should be. 
     pos = (
      circleCenterX + dx - curImg.size[0]/2, 
      circleCenterY + dy - curImg.size[1]/2 
     ) 
     masterImage.paste(curImg, pos) 

img = Image.new("RGB", (500,500), (255,255,255)) 

#red.png, blue.png, green.png are simple 50x50 pngs of solid color 
imageFilenames = ["red.png", "blue.png", "green.png"] * 5 
images = [Image.open(filename) for filename in imageFilenames] 

arrangeImagesInCircle(img, images) 

img.save("output.png") 

结果:

enter image description here

+0

优秀的答案! – btel