2011-04-06 57 views
1

我想绘制一个图像,它将以不同的角度旋转 。旋转后,图像应根据尺寸()放置在显示器 窗口中。我试过用translate(),但我 无法计算动态坐标根据 角度图像已绘制。我的代码看起来像这样如何在显示窗口内定位图像

void setup() 
{ 
    size(600, 600); 
    translate(width/2, height/2); 
    drawTriangles(); 
} 

void drawTriangles() 
{ 
    float deg = 180; 
    float rad = radians(deg); 
    rotate(rad); 
    shapes(5, 15, 75, 55); 
} 

void shapes(int edges, float cx, float cy, float r) 
{ 
    float angle = 360.0/edges; 
    beginShape(); 
    for (int i = 0; i < edges; i++) 
    { 
    vertex(cx + r * cos(radians(angle * i)), cy + r * 
sin(radians(angle * i))); 
    } 
    endShape(CLOSE); 
} 

如何使图像在显示窗口内可见?

回答

1

在旋转图像之前,先找出图像角点。让我们称他们为{C1,C2,C3,C4},坐标存储在一个int [8]:

PImage myimage = ...; 
int w = myimage.width; 
int h = myimage.height; 
int[] coordinates = {0,0, w,0, 0,h, w,h}; 

旋转图像后,这些点会是这个样子:

C1.x' = C1.x * cos(angle) - C1.y * sin(angle); 
C1.y' = C1.x * sin(angle) + C1.y * cos(angle); 
... 

因此,在这个代码看起来像:现在

// buffer the "current" translate/rotate/scale values 
pushMatrix(); 

// rotate the view 
rotate(angle); 

// determine the coordinates for the corners of the rotated image 
int[] rotated_coordinates = new int[8]; 
for(int c=0; c<8; c+=2) { 
    rotated_coordinates[c] = coordinates[c]*cos(angle) - 
           coordinates[c+1]*sin(angle); 
    rotated_coordinates[c+1] = coordinates[c]*sin(angle) + 
           coordinates[c+1]*cos(angle); } 

,以适应您的图像)的大小(所规定的窗口,要重新定位和缩放图像,使所有四个角点触摸的边缘,你窗口;我们能做到这一点,如下所示:

// determine the bounding extremities for the rotated image 
// (replace C1.x' etc. with the rotated_coordinates[] entry) 
int minx = min(min(C1.x',C2.x'),min(C3.x',C4.x')); 
int miny = min(min(C1.y',C2.y'),min(C3.y',C4.y')); 
int maxx = max(max(C1.x',C2.x'),max(C3.x',C4.x')); 
int maxy = max(max(C1.y',C2.y'),max(C3.y',C4.y')); 

// translate so that the minx/y are on the x=0/y=0 lines 
translate(-minx, -miny); 

// scale so that the maxx/y are on the x=width/y=height lines 
scaleX(width/(maxx-minx)); 
scaleY(height/maxy-miny)); 

// draw image 
image(myimage,0,0,width,height); 

// restore the previous translate/rotate/scale values 
popMatrix(); 

所以你在做旋转使用旋转()这两个观点,并手动跟踪的术语,其旋转的结果如何修改图像的角落坐标,以便你可以获得正确的位置。