2012-11-14 164 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