csharp 与ArcObjects一起使用的常用函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 与ArcObjects一起使用的常用函数相关的知识,希望对你有一定的参考价值。

//
// Author : Jacory Gao
//

using System;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using System.Windows.Forms;
using System.Collections.Generic;
using ESRI.ArcGIS.CartoUI;

namespace Global
{
    /// <summary>
    /// 公共方法类
    /// </summary>
    public static class CommonFunctions
    {
        /// <summary>
        /// 根据图层名称获取图层索引号
        /// </summary>
        /// <param name="layerName">图层名称</param>
        /// <returns></returns>
        public static int getLayerIndexByName(string layerName, IMapControlDefault mapControl)
        {
            if (mapControl == null) return -1;
            int index = -1;
            for (int i = 0; i < mapControl.LayerCount; i++)
            {
                if (mapControl.get_Layer(i).Name == layerName)
                {
                    index = i;
                }
            }
            return index;
        }

        /// <summary>
        /// 根据图层名称获取图层对象
        /// </summary>
        /// <param name="name">图层名称</param>
        /// <returns>ILayer图层对象</returns>
        public static ILayer getLayerByName(string name, IMapControlDefault mapControl)
        {
            if (mapControl == null) return null;

            for (int i = 0; i < mapControl.LayerCount; i++)
            {
                ILayer layer = mapControl.get_Layer(i);
                if (name.ToUpper() == layer.Name.ToUpper())
                    return layer;
            }
            return null;
        }

        /// <summary>
        /// 根据图层名称获取图层对象
        /// </summary>
        /// <param name="name">图层名称</param>
        /// <returns>ILayer图层对象</returns>
        public static ILayer getLayerByName(string name, IMap map)
        {
            if (map == null) return null;

            for (int i = 0; i < map.LayerCount; i++)
            {
                ILayer layer = map.get_Layer(i);
                if (layer is IFeatureLayer)
                {
                    if (name.ToUpper() == layer.Name.ToUpper())
                    return layer;
                }
                else if (layer is IGroupLayer)
                {
                    ICompositeLayer pGroupLayer = layer as ICompositeLayer;
                    List<ILayer> temp_layer_list = getlayerbygroup(pGroupLayer, null);
                    for (int j = 0; j < temp_layer_list.Count; j++)
                    {
                        if (temp_layer_list[j].Name == name)
                        {
                            return temp_layer_list[j];
                        }
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 获取一个图层文件的完整绝对路径
        /// </summary>
        /// <param name="layer">图层文件</param>
        /// <returns>完整绝对路径字符串</returns>
        public static string getFullPathForALayer(ESRI.ArcGIS.Carto.ILayer layer)
        {
            if (layer == null || !(layer is ESRI.ArcGIS.Geodatabase.IDataset))
                return null;

            ESRI.ArcGIS.Geodatabase.IDataset dataset = (ESRI.ArcGIS.Geodatabase.IDataset)(layer); // Explicit Cast

            if (dataset.Workspace.Type == esriWorkspaceType.esriFileSystemWorkspace)
                return (dataset.Workspace.PathName + "\\" + dataset.Name + ".shp");
            else if (dataset.Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                return (dataset.Workspace.PathName + "\\" + dataset.Name);

            return (dataset.Workspace.PathName + "\\" + dataset.Name);
        }

        /// <summary>
        /// 判断数据集类型,返回正确的WorkspaceFactory接口
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static IWorkspaceFactory getWorkspaceFactory(string extension)
        {
            extension = extension.ToUpper();

            IWorkspaceFactory pWorkspaceFactory = null;
            Type FactoryType = null;
            switch (extension)
            {
                case "MDB":
                    FactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory");
                    break;
                case "GDB":
                    FactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                    break;
                default:
                    FactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                    break;
            }
            pWorkspaceFactory = Activator.CreateInstance(FactoryType) as IWorkspaceFactory;

            if (extension == "SHP")
                pWorkspaceFactory = new ShapefileWorkspaceFactory();

            return pWorkspaceFactory;
        }

        /// <summary>
        /// 根据R、G、B值获取IColor接口的颜色变量。
        /// </summary>
        /// <param name="red">R分量值</param>
        /// <param name="green">G分量值</param>
        /// <param name="blue">B分量值</param>
        /// <returns>IColor接口的颜色变量</returns>
        public static IColor GetColorByRGBValue(int red, int green, int blue)
        {
            IRgbColor rgbColor = new RgbColorClass();
            rgbColor.Red = red;
            rgbColor.Green = green;
            rgbColor.Blue = blue;
            return rgbColor as IColor;
        }

        /// <summary>
        /// 空间查询,仅查询输入要素图层
        /// </summary>
        /// <param name="feature">输入要素</param>
        /// <param name="spatialEnum">空间关系</param>
        /// <param name="spatialRef">空间参考</param>
        /// <returns>返回要素指针</returns>
        public static IFeatureCursor spatialSearch(IFeature feature, esriSpatialRelEnum spatialEnum, ISpatialReference spatialRef)
        {
            IFeatureClass featureClass = feature.Class as IFeatureClass;

            ISpatialFilter spatialFilter = new SpatialFilter();
            spatialFilter.Geometry = feature.ShapeCopy;
            spatialFilter.SpatialRel = spatialEnum;
            System.String shapeFieldName = featureClass.ShapeFieldName;
            spatialFilter.set_OutputSpatialReference(shapeFieldName, spatialRef);

            IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false);
            return featureCursor;
        }

        ///<summary>Flash geometry on the display. The geometry type could be polygon, polyline, point, or multipoint.</summary>
        ///
        ///<param name="geometry"> An IGeometry interface</param>
        ///<param name="color">An IRgbColor interface</param>
        ///<param name="display">An IDisplay interface</param>
        ///<param name="delay">A System.Int32 that is the time im milliseconds to wait.</param>
        /// 
        ///<remarks></remarks>
        public static void FlashGeometry(IGeometry geometry, IRgbColor color, IDisplay display, System.Int32 delay)
        {
            if (geometry == null || color == null || display == null)
            {
                return;
            }

            display.StartDrawing(display.hDC, (System.Int16)esriScreenCache.esriNoScreenCache); // Explicit Cast

            switch (geometry.GeometryType)
            {
                case esriGeometryType.esriGeometryPolygon:
                    {
                        //Set the flash geometry's symbol.
                        ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass();
                        simpleFillSymbol.Color = color;
                        ISymbol symbol = simpleFillSymbol as ISymbol; // Dynamic Cast
                        symbol.ROP2 = esriRasterOpCode.esriROPNotXOrPen;

                        //Flash the input polygon geometry.
                        display.SetSymbol(symbol);
                        display.DrawPolygon(geometry);
                        System.Threading.Thread.Sleep(delay);
                        display.DrawPolygon(geometry);
                        break;
                    }

                case esriGeometryType.esriGeometryPolyline:
                    {
                        //Set the flash geometry's symbol.
                        ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
                        simpleLineSymbol.Width = 4;
                        simpleLineSymbol.Color = color;
                        ISymbol symbol = simpleLineSymbol as ISymbol; // Dynamic Cast
                        symbol.ROP2 = esriRasterOpCode.esriROPNotXOrPen;

                        //Flash the input polyline geometry.
                        display.SetSymbol(symbol);
                        display.DrawPolyline(geometry);
                        System.Threading.Thread.Sleep(delay);
                        display.DrawPolyline(geometry);
                        break;
                    }

                case esriGeometryType.esriGeometryPoint:
                    {
                        //Set the flash geometry's symbol.
                        ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
                        simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                        simpleMarkerSymbol.Size = 12;
                        simpleMarkerSymbol.Color = color;
                        ISymbol symbol = simpleMarkerSymbol as ISymbol; // Dynamic Cast
                        symbol.ROP2 = esriRasterOpCode.esriROPNotXOrPen;

                        //Flash the input point geometry.
                        display.SetSymbol(symbol);
                        display.DrawPoint(geometry);
                        System.Threading.Thread.Sleep(delay);
                        display.DrawPoint(geometry);
                        break;
                    }

                case esriGeometryType.esriGeometryMultipoint:
                    {
                        //Set the flash geometry's symbol.
                        ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
                        simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                        simpleMarkerSymbol.Size = 12;
                        simpleMarkerSymbol.Color = color;
                        ISymbol symbol = simpleMarkerSymbol as ISymbol; // Dynamic Cast
                        symbol.ROP2 = esriRasterOpCode.esriROPNotXOrPen;

                        //Flash the input multipoint geometry.
                        display.SetSymbol(symbol);
                        display.DrawMultipoint(geometry);
                        System.Threading.Thread.Sleep(delay);
                        display.DrawMultipoint(geometry);
                        break;
                    }
            }
            display.FinishDrawing();
        }

        /// <summary>
        /// 缩放居中当前几何图形
        /// </summary>
        /// <param name="geometry"></param>
        /// <param name="activeView"></param>
        public static void ZoomToGeometry(IGeometry geometry, IActiveView activeView)
        {
            IEnvelope env = geometry.Envelope;
            IGeometry5 geo = geometry as IGeometry5;

            if (env.Width == 0 || env.Height == 0)
            {
                IPoint centerPoint = new PointClass();
                centerPoint.X = geo.CentroidEx.X;
                centerPoint.Y = geo.CentroidEx.Y;

                //IDisplayTransformation displayTrans = activeView.ScreenDisplay.DisplayTransformation;
                //displayTrans.SpatialReference = activeView.FocusMap.SpatialReference;

                env.XMin = centerPoint.X - 0.001;
                env.XMax = centerPoint.X + 0.001;
                env.YMin = centerPoint.Y - 0.001;
                env.YMax = centerPoint.Y + 0.001;
                
                env.CenterAt(centerPoint);
            }
            env.Expand(0.5, 0.5, true);
            activeView.Extent = env;
            activeView.Refresh();
            activeView.ScreenDisplay.UpdateWindow();
        }

        /// <summary>
        /// 得到要素的属性值
        /// </summary>
        /// <param name="feature">要素</param>
        /// <param name="fieldName">属性字段名</param>
        /// <returns>要素属性值</returns>
        public static object getFeatureValue(IFeature feature, string fieldName)
        {
            int index = feature.Fields.FindField(fieldName);
            if (index == -1) return false;

            object val = feature.get_Value(index);

            return val;
        }

        /// <summary>
        /// 设置要素值
        /// </summary>
        /// <param name="feature">要素</param>
        /// <param name="fieldName">属性字段名称</param>
        /// <param name="value">输入值</param>
        /// <param name="save">是否立即存储更改,同时操作多个属性字段值,在操作最后统一存储会更快</param>
        /// <returns></returns>
        /// <returns>成功,返回true。否则返回false</returns>
        public static bool setFeatureValue(IFeature feature, string fieldName, object value, bool save)
        {
            int index = feature.Fields.FindField(fieldName);
            if (index == -1) return false;

            feature.set_Value(index, value);
            if (save == true) { feature.Store(); }

            return true;
        }
        /// <summary>
        /// 获取图层组中的所有要素图层,递归调用
        /// </summary>
        /// <param name="temp_grouplayer"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static List<ILayer> getlayerbygroup(ICompositeLayer temp_grouplayer, List<ILayer> result)
        {
            List<ILayer> temp_layer_list = null;
            if (result == null)
            {
                temp_layer_list = new List<ILayer>();
            }
            else
            {
                temp_layer_list = result;
            }

            for (int j = 0; j < temp_grouplayer.Count; j++)
            {
                ILayer dqlayer = temp_grouplayer.get_Layer(j);
                if (dqlayer is GroupLayer)
                {
                    ICompositeLayer pGroupLayer = dqlayer as ICompositeLayer;
                    temp_layer_list = getlayerbygroup(pGroupLayer, temp_layer_list);
                }
                else if (dqlayer is IFeatureLayer)
                {
                    temp_layer_list.Add(dqlayer);
                }
            }
            return temp_layer_list;
        }

        /// <summary>
        /// 得到地图中所有的矢量要素图层
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        public static List<IFeatureLayer> getAllFeatureLayers(IMap map)
        {
            List<IFeatureLayer> featureLayer = new List<IFeatureLayer>();

            // get all the featurelayers in the map
            if (map == null) return null;
            for (int i = 0; i < map.LayerCount; i++)
            {
                ILayer layer = map.get_Layer(i);
                if (layer == null || !layer.Valid) continue;

                if (layer is IFeatureLayer)
                {
                    featureLayer.Add(layer as IFeatureLayer);
                }
                else if (layer is IGroupLayer)
                {
                    ICompositeLayer pGroupLayer = layer as ICompositeLayer;
                    List<ILayer> temp_layer_list = getlayerbygroup(pGroupLayer, null);
                    for (int j = 0; j < temp_layer_list.Count; j++)
                    {
                        if (temp_layer_list[j] is IFeatureLayer)
                        {
                            featureLayer.Add(temp_layer_list[j] as IFeatureLayer);
                        }
                    }
                }
            }
            return featureLayer;
        }

        /// <summary>
        /// 采用要素查询的方式闪烁要素
        /// </summary>
        /// <param name="_activeView"></param>
        /// <param name="_feature"></param>
        public static void identifyFlash(IActiveView _activeView, IFeature _feature)
        {
            IActiveView activeView = _activeView;
            IFeatureIdentifyObj featIdentify = new FeatureIdentifyObject();
            featIdentify.Feature = _feature;
            IIdentifyObj identify = featIdentify as IIdentifyObj;
            identify.Flash(activeView.ScreenDisplay);
        }

        /// <summary>
        /// 要素空间分析
        /// </summary>
        /// <param name="inputFeature"></param>
        /// <param name="targetLayers"></param>
        /// <param name="spatialEnum"></param>
        /// <param name="spatialRef"></param>
        /// <returns></returns>
        public static List<IFeature> doSpatialSearch(IFeature inputFeature, List<IFeatureLayer> targetLayers,
            esriSpatialRelEnum spatialEnum, ISpatialReference spatialRef)
        {
            List<IFeature> resFeature = new List<IFeature>();

            foreach (IFeatureLayer targetLayer in targetLayers)
            {
                IFeatureClass featureClass = targetLayer.FeatureClass as IFeatureClass;
                if (featureClass == null) continue;

                ISpatialFilter spatialFilter = new SpatialFilter();
                spatialFilter.Geometry = inputFeature.ShapeCopy;
                spatialFilter.SpatialRel = spatialEnum;
                System.String shapeFieldName = featureClass.ShapeFieldName;
                spatialFilter.set_OutputSpatialReference(shapeFieldName, spatialRef);

                IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false);
                IFeature feature = null;
                while ((feature = featureCursor.NextFeature()) != null)
                {
                    if (feature.OID == inputFeature.OID)
                        continue;
                    resFeature.Add(feature);
                }
            }

            return resFeature;
        }
    }
}

以上是关于csharp 与ArcObjects一起使用的常用函数的主要内容,如果未能解决你的问题,请参考以下文章

Python 中的 COM 对象(arcobjects)

csharp 自定义需要可能与dict一起使用的验证器。

csharp 与Umbraco ContentService一起使用的嵌套内容项的模型

csharp 将LibLog与Microsoft.Owin.Logging一起使用

ArcObjects中IMapAlgebraOp的使用体会

使用 ArcGIS中的ArcObjects进行二次开发