processing - 处理 - 如何加载 .txt 文件并绘制 2d 形状?
问题描述
我不确定如何绘制文本文件中包含的形状。我想使用 loadStrings 将数据加载到文本文件中并绘制相应的 2d 形状。
请帮忙
txt 文件为“data.txt”,内容为:
ellipse 100,100,80,50
line 20,30,120,150
rect 0,100,50,70
解决方案
要绘制数据文件中指定的形状,我们可以
- 选择文件格式,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);
}
}
}
推荐阅读
- matlab - 导致旋转弧接触另一条曲线而不相交(Matlab代码)
- c# - 在文件上传中添加日期过滤器,同时单击 asp.net 网络表单中的文件上传按钮
- reactjs - React Native:createBottomTabNavigator screenOptions 不起作用
- harmon.ie - 通过harmon.ie 保存电子邮件 - 如果查看邮件的人没有前景怎么办?
- r - R Shiny - 将 JS 文件添加到 HTML 模板
- powershell - 我尝试使用 power shell 下载图像文件,但出现以下错误
- python - 在 Docker Hub 上找不到合适的图像,而它在 Bitbucket 上似乎运行正常
- opengl - OpenGL绘制多个对象
- php - 使用 WriteHtml -PHP 支持中文、日文和英文的 TCPDF 字体
- javascript - 如何从嵌套数组中删除对象?