C# AE 合并要素/合并图形/merger功能

92 篇文章 6 订阅

功能描述

合并功能,准确的说是merge、union。

这两者在ArcMap中的差别就是:merger保留相同字段属性;union是可以选择创建新的合并图形还是直接用原始要素合并,合并属性不保留。

接口和使用方法

1.

ITopologicalOperator接口,其下的ConstructUnion属性能够一次放入多个几何(ConstructUnion属性是将放入的所有几何能够被一次性合并,这种方式比反复调用合并更加高效。其参数只能是IEnumGeometry(包络几何),可以将IGeometryCollection转为IEnumGeometry),然后直接在FeatureClass中创建Feature,ITopologicalOperator as为IGeometry即可。

2.

ITopologicalOperator接口,其下有union方法。

3.

IBasicGeoprocessor 接口。其下有

CancelTracker     The cancel tracker.
Clip            Clips features.
Dissolve          Dissolves features.
Intersect         Intersects features.
Merge          Merges features.
SpatialReference     The output spatial reference.
Union        Creates a union of features.

4.

GP接口

5.其他

具体代码

方法1代码:

1
2
3
4
5
6
private void btnMerge_Click( object sender, EventArgs e)
       {
               ICommand pUnionFeature = new UnionFeatures(0);
               pUnionFeature.OnCreate(axMapControl1.Object);
               axMapControl1.CurrentTool = pUnionFeature as ITool;
        }

新建类UnionFeatures.cs

代码如下


using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;


namespace WindowsFormsApplication2
{

    /// <summary>
    /// Summary description for UnionFeatures.
    /// </summary>
    [Guid("af0c15f2-8963-4fa7-b754-0f65e7b3c4bd")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("lyx.UnionFeatures")]
    public sealed class UnionFeatures : BaseTool
    {
        #region COM Registration Function(s)
        [ComRegisterFunction()]
        [ComVisible(false)]
        static void RegisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryRegistration(registerType);

            //
            // TODO: Add any COM registration code here
            //
        }

        [ComUnregisterFunction()]
        [ComVisible(false)]
        static void UnregisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryUnregistration(registerType);

            //
            // TODO: Add any COM unregistration code here
            //
        }

        #region ArcGIS Component Category Registrar generated code
        /// <summary>
        /// Required method for ArcGIS Component Category registration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryRegistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            MxCommands.Register(regKey);
            ControlsCommands.Register(regKey);
        }
        /// <summary>
        /// Required method for ArcGIS Component Category unregistration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryUnregistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            MxCommands.Unregister(regKey);
            ControlsCommands.Unregister(regKey);
        }

        #endregion
        #endregion

        IHookHelper m_hookHelper = null;
        IActiveView m_activeView = null;
        IMap m_map = null;
        IFeatureLayer currentLayer = null;
        //IEngineEditProperties m_engineEditor = null;
        int p;
        public UnionFeatures(int _p)
        {
            //
            // TODO: Define values for the public properties
            //
            base.m_category = ""; //localizable text 
            base.m_caption = "";  //localizable text 
            base.m_message = "This should work in ArcMap/MapControl/PageLayoutControl";  //localizable text
            base.m_toolTip = "";  //localizable text
            base.m_name = "";   //unique id, non-localizable (e.g. "MyCategory_MyTool")
            //m_engineEditor = new EngineEditorClass();
            p = _p;
            try
            {
                //
                // TODO: change resource name if necessary
                //
                string bitmapResourceName = GetType().Name + ".bmp";
                base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
                base.m_cursor = new System.Windows.Forms.Cursor(GetType(), GetType().Name + ".cur");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
            }
        }

        #region Overriden Class Methods

        /// <summary>
        /// Occurs when this tool is created
        /// </summary>
        /// <param name="hook">Instance of the application</param>
        public override void OnCreate(object hook)
        {
            try
            {
                m_hookHelper = new HookHelperClass();
                m_hookHelper.Hook = hook;
                if (m_hookHelper.ActiveView == null)
                {
                    m_hookHelper = null;
                }
            }
            catch
            {
                m_hookHelper = null;
            }

            if (m_hookHelper == null)
                base.m_enabled = false;
            else
                base.m_enabled = true;

            // TODO:  Add other initialization code
        }

        /// <summary>
        /// Occurs when this tool is clicked
        /// </summary>
        public override void OnClick()
        {
            m_activeView = m_hookHelper.ActiveView;
            m_map = m_hookHelper.FocusMap;

            ILayer layer = m_map.get_Layer(p);
            if (layer != null)
            { MessageBox.Show(m_map.SelectionCount.ToString(), "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; }

            IEnumFeature selectedFeatures = GetSelectedFeatures();
            if (selectedFeatures == null) return;
            UnionFeature(selectedFeatures);
            m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection, null, m_activeView.Extent);
        }
        private IEnumFeature GetSelectedFeatures()
        {
            //if (m_map.SelectionCount < 2)
            //{
            //    MessageBox.Show("无图层操作!!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return null;
            //}
            ILayer layer = m_map.get_Layer(p);
            if (layer == null)
                return null;
            if (!(layer is IFeatureLayer))
                return null;
            currentLayer = layer as IFeatureLayer;
            if (currentLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                MessageBox.Show("无图层操作!!!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }
            IEnumFeature SelectedFeatures = m_map.FeatureSelection as IEnumFeature;
            if (SelectedFeatures == null) return null;
            //判断SelectedFeatures是否为相同的几何类型,且是否与m_engineEditor.TargetLayer几何类型相同
            bool sameGeometryType = JudgeGeometryType(SelectedFeatures);
            if (!sameGeometryType)
            { MessageBox.Show("无图层操作!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return null; }
            return SelectedFeatures;
        }
        private bool JudgeGeometryType(IEnumFeature SelectedFeatures)
        {
            SelectedFeatures.Reset();
            IFeature feature = SelectedFeatures.Next();
            if (feature == null) return false;
            esriGeometryType geometryType = feature.ShapeCopy.GeometryType;
            while ((feature = SelectedFeatures.Next()) != null)
            {
                if (geometryType != feature.ShapeCopy.GeometryType)
                { return false; }
            }
            if (geometryType == currentLayer.FeatureClass.ShapeType)
                return true;
            return false;
        }
        private void UnionFeature(IEnumFeature selectedFeatures)
        {
            IFeature feature = null;
            IGeometry geometry = null;
            object missing = Type.Missing;
            selectedFeatures.Reset();
            feature = selectedFeatures.Next();
            if (feature == null) return;
            IFeatureClass featureClass = feature.Class as IFeatureClass;
            IGeometryCollection geometries = new GeometryBagClass();
            while (feature != null)
            {
                geometry = feature.ShapeCopy;
                geometries.AddGeometry(geometry, ref missing, ref missing);
                feature = selectedFeatures.Next();
            }
            ITopologicalOperator unionedGeometry = null;
            switch (featureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryMultipoint:
                    unionedGeometry = new MultipointClass(); break;
                case esriGeometryType.esriGeometryPolyline:
                    unionedGeometry = new PolylineClass(); break;
                case esriGeometryType.esriGeometryPolygon:
                    unionedGeometry = new PolygonClass(); break;
                default: break;
            }
            unionedGeometry.ConstructUnion(geometries as IEnumGeometry);
            ITopologicalOperator2 topo = unionedGeometry as ITopologicalOperator2;
            topo.IsKnownSimple_2 = false;
            topo.Simplify();
            IFeatureClass targetFeatureClass = currentLayer.FeatureClass;
            IDataset dataset = featureClass as IDataset;
            IWorkspaceEdit workspaceEdit = dataset.Workspace as IWorkspaceEdit;
            if (!(workspaceEdit.IsBeingEdited())) return;
            try
            {
                workspaceEdit.StartEditOperation();
                IFeature unionedFeature = targetFeatureClass.CreateFeature();
                unionedFeature.Shape = unionedGeometry as IGeometry;
                unionedFeature.Store();
                workspaceEdit.StopEditOperation();
            }
            catch (Exception ex)
            {
                workspaceEdit.AbortEditOperation();
                MessageBox.Show("要素合并失败!!" + ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add UnionFeatures.OnMouseDown implementation
        }

        public override void OnMouseMove(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add UnionFeatures.OnMouseMove implementation
        }

        public override void OnMouseUp(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add UnionFeatures.OnMouseUp implementation
        }
        #endregion
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值