如何在显示窗口内定位图像

时间:2011-04-06 09:15:26

标签: processing.js

我正在尝试绘制图像,它将以不同方式旋转 角。旋转后,图像应位于显示器中 窗口根据大小()。我尝试使用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 个答案:

答案 0 :(得分: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();

因此,您正在使用rotate()旋转两个视图,并根据修改图像角坐标的方式手动跟踪旋转的结果,以便您可以正确放置位置。