#include<gdal_priv.h>
#include<iostream>
#include <ogr_spatialref.h>
#include "ogrsf_frmts.h"
int MakeDxfFile() {
CPLSetConfigOption("GDAL_DATA", "D:\\make\\gdal_64bit\\data");
const char* pszDriverName = "DXF";
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
RegisterOGRDXF();
GDALAllRegister();
//读取
//GDALDataset* dataset = (GDALDataset*)GDALOpenEx(_vectorpath, GDAL_OF_READONLY, NULL, NULL, NULL);
GDALDriver* poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);
if (poDriver == NULL)
{
printf("%s driver not available.\n", pszDriverName);
exit(1);
}
GDALDataset* poDS;
// 模板文件名称,文件在GDAL中data下,拷贝到与cpp同目录下
/*char** papszOptions = (char**)CPLCalloc(sizeof(char*), 3);
papszOptions[0] = (char*)"HEADER=header.dxf";
papszOptions[1] = (char*)"TRAILER=trailer.dxf";*/
poDS = poDriver->Create((const char*)"out.dxf", 0, 0, 0, GDT_Unknown, NULL); //创建输出矢量文件
//CPLFree(papszOptions);
if (poDS == NULL)
{
printf("Creation of output file failed.\n");
GDALClose((GDALDatasetH)poDS);
exit(1);
}
OGRLayer* poLayer;
poLayer = poDS->CreateLayer("hatch_out", NULL, wkbUnknown, NULL);
if (poLayer == NULL)
{
printf("Layer creation failed.\n");
exit(1);
}
OGRFeature* poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
// 生成一个正方形,放置在"Square"图层
OGRLinearRing oSquare;
oSquare.addPoint(0.0, 0.0);
oSquare.addPoint(10.0, 0.0);
oSquare.addPoint(10.0, 10.0);
oSquare.addPoint(0.0, 10.0);
oSquare.closeRings();
poFeature->SetField("Layer", "Square");
poFeature->SetGeometry(&oSquare);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
{
printf("Failed to create feature in dxffile.\n");
exit(1);
}
// 生成一个三角形,放置在"三角形"图层
poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
OGRLinearRing oTriangle;
oTriangle.addPoint(20.0, 20.0);
oTriangle.addPoint(30.0, 20.0);
oTriangle.addPoint(30.0, 30.0);
oTriangle.closeRings();
poFeature->SetField("Layer", "Triangle");
poFeature->SetGeometry(&oTriangle);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
{
printf("Failed to create feature in dxffile.\n");
exit(1);
}
// 生成一个菱形,放置在"Triangle"图层
poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
OGRLinearRing oRhombus;
oRhombus.addPoint(40.0, 30.0);
oRhombus.addPoint(50.0, 40.0);
oRhombus.addPoint(40.0, 50.0);
oRhombus.addPoint(30.0, 40.0);
oRhombus.closeRings();
poFeature->SetField("Layer", "Triangle");
poFeature->SetGeometry(&oRhombus);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
{
printf("Failed to create feature in dxffile.\n");
exit(1);
}
// 生成一个多段线,不设置图层,将默认层
poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
OGRLinearRing oLinearRing;
oLinearRing.addPoint(50.0, 50.0);
oLinearRing.addPoint(60.0, 40.0);
oLinearRing.addPoint(70.0, 50.0);
oLinearRing.addPoint(80.0, 40.0);
poFeature->SetGeometry(&oLinearRing);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
{
printf("Failed to create feature in dxffile.\n");
exit(1);
}
OGRFeature::DestroyFeature(poFeature);
GDALClose((GDALDatasetH)poDS);
}