昨天下载了GDAL1.9.2。意外发现OGRDXFWriterLayer类中多了一个OGRErr WriteHATCH( OGRFeature *poFeature, OGRGeometry *poGeom )函数,而在OGRErr CreateFeature( OGRFeature *poFeature )函数中使用WriteHATCH条件是:
if( eGType == wkbPolygon || eGType == wkbMultiPolygon )
{
if( bWriteHatch )
return WriteHATCH( poFeature );
else
return WritePOLYLINE( poFeature );
}
而在OGRDXFWriterLayer的构造函数中有bWriteHatch = CSLTestBoolean(CPLGetConfigOption("DXF_WRITE_HATCH", "YES"));
所以生成HATCH条件是要素必须是多边形或者是多多边形,并且要设置CPLSetConfigOption("DXF_WRITE_HATCH", "YES")。下面来试一下吧。
绘制一个红色的四边形试试:
#include "ogrsf_frmts.h"
#include "stdio.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char *pszDriverName = "DXF";
OGRSFDriver *poDriver;
CPLSetConfigOption("DXF_WRITE_HATCH", "YES"); // 设置绘制填充多边形
RegisterOGRDXF();
poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(
pszDriverName );
if( poDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
OGRDataSource *poDS;
// 模板文件名称,文件在GDAL中data下,拷贝到与cpp同目录下,按下设置,也可以设置一个正确的相对路径和绝对路径
char **papszOptions = (char **)CPLCalloc(sizeof(char *),3);
papszOptions[0] = "HEADER=header.dxf";
papszOptions[1] = "TRAILER=trailer.dxf";
poDS = poDriver->CreateDataSource( "hatch_out.dxf", papszOptions );
CPLFree(papszOptions);
if( poDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
OGRLayer *poLayer;
poLayer = poDS->CreateLayer( "hatch_out", NULL, wkbUnknown, NULL );
if( poLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
OGRFeature *poFeature;
poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() );
poFeature->SetField("Layer","正方形");
// 生成一个正方形
OGRPolygon oPolygon;
OGRLinearRing oLinearRing;
oLinearRing.addPoint(0.0,0.0);
oLinearRing.addPoint(1.0,0.0);
oLinearRing.addPoint(1.0,1.0);
oLinearRing.addPoint(0.0,1.0);
oLinearRing.closeRings();
oPolygon.addRing(&oLinearRing);
poFeature->SetGeometry( &oPolygon );
// 设置样式字符串,第一个样式必须是画刷
char strStyle[256];
sprintf(strStyle,"BRUSH(fc:#%02x%02x%02x)",
255, // 红色分量
0, // 绿色分量
0); // 蓝色分量
poFeature->SetStyleString( strStyle );
if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
OGRFeature::DestroyFeature( poFeature );
OGRDataSource::DestroyDataSource( poDS );
}
运行程序生成一个hetch_out.dxf文件使用AUTO CAD打开:
在oPolygon.addRing(&oLinearRing);后面添加下面代码:
// 添加一个内环 也就是CAD中的孤岛
OGRLinearRing oInteriorRing;
oInteriorRing.addPoint(0.2,0.2);
oInteriorRing.addPoint(0.2,0.4);
oInteriorRing.addPoint(0.4,0.4);
oInteriorRing.closeRings();
oPolygon.addRing(&oInteriorRing);
运行程序,(主要要把上面用AUTO CAD打开的hetch_out.dxf关掉,不然会创建数据源失败)生成hetch_out.dxf文件使用AUTO CAD打开: