Processing 处理-如何加载.txt文件并绘制二维形状?

Processing 处理-如何加载.txt文件并绘制二维形状?,processing,Processing,我不知道如何绘制包含在文本文件中的形状。 我想使用loadStrings在文本文件中加载数据并绘制相应的二维形状 请帮忙 txt文件是“data.txt” 内容包括: ellipse 100,100,80,50 line 20,30,120,150 rect 0,100,50,70 要绘制数据文件中指定的形状,我们可以 选择文件格式,csv将很好地工作,但我们也可以使用文本文件 确定要使用的形状属性。对于这个例子,我们将只使用形状、x、y、宽度和高度。我们还可以指定诸如颜色和透明度之类的内容

我不知道如何绘制包含在文本文件中的形状。 我想使用loadStrings在文本文件中加载数据并绘制相应的二维形状

请帮忙

txt文件是“data.txt” 内容包括:

ellipse 100,100,80,50
line 20,30,120,150
rect 0,100,50,70

要绘制数据文件中指定的形状,我们可以

  • 选择文件格式,csv将很好地工作,但我们也可以使用文本文件
  • 确定要使用的形状属性。对于这个例子,我们将只使用形状、x、y、宽度和高度。我们还可以指定诸如颜色和透明度之类的内容
  • 编写读取文件的代码。如果我们使用csv格式,处理可以读取带有
    loadStrings
    的文本文件。处理将使事情变得更加简单
  • 编写绘制形状的代码
在第一个示例中,我们将按如下方式格式化数据文件:

ellipse,110,100,80,50
line,170,30,150,150
rect,10,100,50,70
ellipse,110,200,50,50
我们可以选择任何我们喜欢的东西,包括空格来分隔元素。这是我们的comas。该文件保存为草图文件夹中的shape_data.txt

守则:

// since we use position in our data to keep track of what each element is
// we name an index into each element
int shapeIndex = 0;
int xIndex = 1;
int yIndex = 2;
int widthIndex = 3;
int heightIndex = 4;

void setup() {
  size(900, 900);
  background(0);
  fill(255);
  stroke(255);
  String [] shapeRows = loadStrings("shape_data.txt");
  for (String s : shapeRows){
    String [] elements = s.split(",");
    int x = Integer.parseInt(elements[xIndex]);
    int y = Integer.parseInt(elements[yIndex]);
    int shapeWidth = Integer.parseInt(elements[widthIndex]);
    int shapeHeight = Integer.parseInt(elements[heightIndex]);
    String shape = elements[shapeIndex];
    if ("ellipse".equals(shape)){
      ellipse(x,y,shapeWidth,shapeHeight);
    } else if ("line".equals(shape)){
      line(x,y,shapeWidth,shapeHeight);
    } else if ("rect".equals(shape)){
      rect(x,y,shapeWidth,shapeHeight);
    }
  }
下一个示例使用csv文件而不是纯文本文件。数据仍然是纯文本,我们仍然依赖于元素的位置,但我们得到的优势是元素是命名的,并且名称存储在文件头中

csv文件如下所示,我们将其保存为
shape\u data.csv
,与草图保存在同一文件夹中

shape,x,y,width,height
ellipse,110,100,80,50
line,170,30,150,150
rect,10,100,50,70
ellipse,110,200,50,50
以及守则:

Table table;

void setup() {
  size(900, 900);
  table = loadTable("shape_data.csv", "header");
  background(0);
  fill(255);
  stroke(255);
  for (TableRow row : table.rows()) {
    int x = row.getInt("x");
    int y = row.getInt("y");
    int shapeWidth = row.getInt("width");
    int shapeHeight = row.getInt("height");
    String shape = row.getString("shape");
    if ("ellipse".equals(shape)){
      ellipse(x,y,shapeWidth,shapeHeight);
    } else if ("line".equals(shape)){
      line(x,y,shapeWidth,shapeHeight);
    } else if ("rect".equals(shape)){
      rect(x,y,shapeWidth,shapeHeight);
    }
  }
}
当我们运行任一草图时,我们将看到: