首页 > 解决方案 > 处理 - 如何加载 .txt 文件并绘制 2d 形状?

问题描述

我不确定如何绘制文本文件中包含的形状。我想使用 loadStrings 将数据加载到文本文件中并绘制相应的 2d 形状。

请帮忙

txt 文件为“data.txt”,内容为:

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

标签: processing

解决方案


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

  • 选择文件格式,csv 可以很好地工作,但我们也可以使用文本文件
  • 决定使用哪些形状属性。对于这个例子,我们将只使用形状、x、y、宽度和高度。我们还可以指定颜色和透明度等内容。
  • 编写读取文件的代码。处理可以读取文本文件loadStrings如果我们使用 csv 格式处理将使事情变得更容易。
  • 编写绘制形状的代码

在第一个示例中,我们将像这样格式化我们的数据文件:

ellipse,110,100,80,50
line,170,30,150,150
rect,10,100,50,70
ellipse,110,200,50,50

我们可以选择任何我们喜欢的东西,包括空格来分隔元素。在这里,我们昏迷了。该文件在我们的草图文件夹中保存为 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_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);
    }
  }
}

当我们运行任一草图时,我们将看到: 从 csv 文件中绘制的形状


推荐阅读