如何在Processing中以一定角度绘制字符串对象?

时间:2013-10-31 09:39:38

标签: processing

下面的代码使用字符串数组中的对象绘制螺旋线。一切都很好,除了我希望文本对象在每个实例上以大约45度角绘制(基于下面代码中的当前x,y坐标)而不是水平绘制(当文本水平绘制时) ,它自然地与沿着曲线的顶部和底部的集中点处的其他文本重叠。我研究了一些方法,但我对所有这些方法仍然很陌生,潜在的解决方案都让我想起了。

String example = "";

String[] wordSet = split(example, " ");

float x, y;
float angle = 0;
float radiusSpiralLine = 10;

size (800, 800);
translate(width/2, height/2);
background(#ffffff);
smooth();
fill(0);

for (int i = 0; i < wordSet.length; i++) {


  angle += .05;
  radiusSpiralLine += .5;

  x = cos(angle) * radiusSpiralLine;
  y = sin(angle) * radiusSpiralLine;

  textSize(9);
  text(wordSet[i], x, y);

}

2 个答案:

答案 0 :(得分:1)

Here is tutorial非常相似的问题。基本上你需要通过pushMatrix()存储投影矩阵,然后根据曲线上字母的位置进行平移和旋转,然后通过popMatrix()恢复矩阵。我不知道你想要如何旋转你的文字,只是围绕你的text()函数折叠,这可能会对你有所帮助:

pushMatrix();
translate(x, y);
rotate(angle);
text(wordSet[i], 0, 0);
popMatrix(); 

答案 1 :(得分:0)

首先,您应该开始养成在setup()draw()函数中包装代码的习惯。由于您正在绘制静态图像,因此不需要draw()函数,但我认为将这两个函数设置为好的做法。

现在,你现在正在做的只是简单地翻译单词。算一算:

x = cos(angle) * radiusSpiralLine; //cos(.05)*.5 = .499
y = sin(angle) * radiusSpiralLine; //sin(.05)*.5 = .024

这意味着它们移动不到一个像素,而且它们根本不会旋转。

你需要的是你的好朋友,rotate()功能。

让我们重写代码:

String example = "These are a bunch of words going around!";
String[] wordSet = split(example, " ");
float x, y;
float angle = 0;

void setup() {
  size (800, 800);
  background(#ffffff);
  smooth();
  fill(0);
  pushMatrix();
  translate(width/2, height/2); //Translate when you need to translate, not before
  for (int i = 0; i < wordSet.length; i++) {
    angle = PI/5; //Our good friends, radians
    textSize(20); //What is this, text for ants? Change to 20  
    rotate(angle);
    text(wordSet[i], 20, 0);
  }
  popMatrix();
}

void draw() {
}

首先注意,setup()draw()。我喜欢他们。我认为它看起来更好。

需要注意的几件重要事项。 rotate()translate()在画布上的效果是累积的。 我们可以用不同的方式产生同样的效果:

  for (int i = 0; i < wordSet.length; i++) {
    angle = PI/5;
    textSize(20);
    rotate(angle); //always rotating by PI/5 ON TOP of previous rotation
    text(wordSet[i], 20, 0);
  }
//Everything from now on will still be rotated, we don't want that!

稍微好一些,但还没有:

  for (int i = 0; i < wordSet.length; i++) {
    angle += PI/5; //constantly increasing the angle
    textSize(20); 
    pushMatrix(); //push a new canvas on top of everything
    rotate(angle); //rotate by angle (which increases every loop)
    text(wordSet[i], 20, 0);
    popMatrix(); //pop the rotated canvas out, go back to original canvas
  } //Things won't be rotated, but they'll still be translated, since translate() is outside of pushMatrix and popMatrix

希望这会有所帮助。