【注】用到的关键函数见Union函数,主要接口就是ITopologicalOperator4
private void StartUnion(object sender, EventArgs e)
{
ILayer pLyrSelect = null;
IFeatureClass pFeaClass = null;
IFeature pFea = null;
IFeatureCursor pFeaCursor = null;
//IQueryFilter pFilter = null;
IWorkspace pWorkspace = null;
//IDataset pDataset = null;
IFeatureSelection pFeaSelection = null;
ISelectionSet pSelectionSet = null;
ICursor pCursor = null;
List<IFeature> ListFeat = new List<IFeature>();
ListFeat.Clear();
pLyrSelect = (m_pMapCtrl as IMapControl3).CustomProperty as ILayer;//得到选中的图层
pFeaSelection = pLyrSelect as IFeatureSelection;
if (pFeaSelection.SelectionSet.Count <= 0)
{
MessageBox.Show("图层没有选择要素,请先选择要合并的要素", "提示");
return;
}
else
{
pSelectionSet = pFeaSelection.SelectionSet;
pSelectionSet.Search(null, false, out pCursor);
pFeaCursor = pCursor as IFeatureCursor;
pFea = pFeaCursor.NextFeature();
while (pFea != null)
{
ListFeat.Add(pFea);
pFea = pFeaCursor.NextFeature();
}
}
IFeature[] pFeaArry = ListFeat.ToArray();
IGeometry pGeoUnion = Union(pFeaArry);
pWorkspace = (pFeaClass as IDataset).Workspace;
IWorkspaceEdit pWorkspaceEdit = pWorkspace as IWorkspaceEdit;
//开始编辑操作工序
pWorkspaceEdit .StartEditing(true);
pWorkspaceEdit .StartEditOperation();
IFeature pFeaNew = null;
pFeaNew = pFeaClass.CreateFeature();
if (pFeaNew == null) return;
pFeaNew.Shape = pGeoUnion;
//保存数据
pFeaNew.Store();
//删除原来的合并前对象
for (int i = ListFeat.Count - 1; i >= 0; i--)
{
pFea = ListFeat[i];
pFea.Delete();
ListFeat.Remove(pFea);
}
ListFeat.Clear();
//结束编辑操作工序
pWorkspaceEdit .StopEditOperation();
pWorkspaceEdit .StopEditing(true);
m_pMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, pLyrSelect, pGeoUnion.Envelope);
}
public IGeometry Union(IFeature[] FeatureArray)
{
IGeometry pGeoUnion = null;
IPointCollection pPtCollArry = null;
int nPtCount = 0;
try
{
if (FeatureArray.Length > 0)
{
pGeoUnion = FeatureArray[0].ShapeCopy;
IGeometry NextGeo = null;
ITopologicalOperator4 pTopoUnion = null;
for (int i = 1; i < FeatureArray.Length; i++)
{
pTopoUnion = (ITopologicalOperator4)pGeoUnion;
pTopoUnion.Simplify();//拓扑处理
NextGeo = FeatureArray[i].ShapeCopy;
NextGeo.SnapToSpatialReference();
ITopologicalOperator4 pTopoNext = (ITopologicalOperator4)NextGeo;
pTopoNext.IsKnownSimple_2 = false;
pTopoNext.Simplify();//拓扑处理
pGeoUnion = pTopoUnion.Union(NextGeo);
}
pPtCollArry = pGeoUnion as IPointCollection;
nPtCount = pPtCollArry.PointCount;
}
}
catch (Exception ee)
{
pGeoUnion = null;
System.Diagnostics.Debug.WriteLine(ee.Message);
}
return pGeoUnion;
}