Beispiel #1
0
        /// <summary>
        /// Loads layer from datasource specifed by filename
        /// </summary>
        private void LoadLayer()
        {
            axMap1.RemoveAllLayers();
            int    handle = -1;
            string ext    = System.IO.Path.GetExtension(m_filename).ToLower();

            if (ext == ".shp")
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(m_filename, null))
                {
                    handle = axMap1.AddLayer(sf, true);
                    sf.Labels.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    sf.Charts.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                }
            }
            else
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                if (img.Open(m_filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, null))
                {
                    handle = this.axMap1.AddLayer(img, true);
                }
            }

            // serializing initial state to display random options afterwrads
            m_initState = axMap1.SerializeLayer(handle);
        }
        /// <summary>
        /// Will convolve the SourceImage specified using the filter specified, returning the result in a new image
        /// as the ref parameter DestImage.
        /// </summary>
        /// <param name="SourceImage">A MapWinGIS.Image object to be processed</param>
        /// <param name="DestImage">The output MapWinGIS.Image object from this process</param>
        /// <param name="filter">The 2D float array of filter coefficients to use (Row Major)</param>
        /// <param name="ShowProgressDialog">If true, will show progress in a typical dialog form</param>
        /// <param name="ICallBack">If specified, will return data as a MapWinGIS.ICallBack object</param>
        /// <returns>Boolean, false if the process was canceled.</returns>
        public static bool ApplyFilter(MapWinGIS.Image SourceImage, ref MapWinGIS.Image DestImage, float[,] filter, bool ShowProgressDialog, MapWinGIS.ICallback ICallBack)
        {
            // Report unnamed as differently from null
            string SourceFile = "null";
            string DestFile   = "null";

            if (SourceImage != null)
            {
                SourceFile = SourceImage.Filename;
                if (SourceFile == null)
                {
                    SourceFile = "Unnamed";
                }
            }
            if (DestImage != null)
            {
                DestFile = SourceImage.Filename;
                if (DestFile == null)
                {
                    DestFile = "Unnamed";
                }
            }
            MapWinUtility.Logger.Dbg("ApplyFilter(SourceImage: " + SourceFile + ",\n" +
                                     "            DestImage: " + DestFile + ",\n" +
                                     "            filter: [" + filter.GetUpperBound(0) + ", " + filter.GetUpperBound(1) + "],\n" +
                                     "            ShowProgressDialog: " + ShowProgressDialog.ToString() + ",\n" +
                                     "            ICallback)");

            return(Do_ApplyFilter(SourceImage, ref DestImage, filter, ShowProgressDialog, ICallBack));
        }
        /// <summary>
        /// Will convolve the SourceImage specified using the filter specified, returning the result in a new image
        /// as the ref parameter DestImage.
        /// </summary>
        /// <param name="SourceImage">A MapWinGIS.Image object to be processed</param>
        /// <param name="DestImage">The output MapWinGIS.Image object from this process</param>
        /// <param name="filter">The 2D float array of filter coefficients to use (Row Major)</param>
        /// <returns>Boolean, false if the process was canceled.</returns>
        public static bool ApplyFilter(MapWinGIS.Image SourceImage, ref MapWinGIS.Image DestImage, float[,] filter)
        {
            // Report unnamed as differently from null
            string SourceFile = "null";
            string DestFile   = "null";

            if (SourceImage != null)
            {
                SourceFile = SourceImage.Filename;
                if (SourceFile == null)
                {
                    SourceFile = "Unnamed";
                }
            }
            if (DestImage != null)
            {
                DestFile = SourceImage.Filename;
                if (DestFile == null)
                {
                    DestFile = "Unnamed";
                }
            }
            MapWinUtility.Logger.Dbg("ApplyFilter(SourceImage: " + SourceFile + ",\n" +
                                     "            DestImage: " + DestFile + ",\n" +
                                     "            filter: [" + filter.GetUpperBound(0) + ", " + filter.GetUpperBound(1) + "])");


            return(Do_ApplyFilter(SourceImage, ref DestImage, filter, true, null));
        }
        /// <summary>
        /// Loads layer from datasource specifed by filename
        /// </summary>
        private void LoadLayer()
        {
            axMap1.RemoveAllLayers();

            int    handle = -1;
            string ext    = System.IO.Path.GetExtension(m_layer.FileName).ToLower();

            if (ext == ".shp")
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(m_layer.FileName, null))
                {
                    handle = axMap1.AddLayer(sf, true);
                    sf.Labels.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    sf.Charts.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    //sf.FastMode = true;
                }
            }
            else
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                if (img.Open(m_layer.FileName, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, null))
                {
                    handle = this.axMap1.AddLayer(img, true);
                }
            }
        }
Beispiel #5
0
        private void menu_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title = "Mo tap tin du lieu";
            //ofd.Filter = "*.shp|*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (ofd.FileName.ToLower().EndsWith(".shp"))
                {
                    MapWinGIS.Shapefile tmpSf = new Shapefile();
                    var result  = tmpSf.Open(@ofd.FileName, null);
                    int iHandle = axMap1.AddLayer(tmpSf, true);
                    AddLayer(axMap1.get_LayerName(iHandle));
                }
                else if (ofd.FileName.ToLower().EndsWith(".tif") ||
                         ofd.FileName.ToLower().EndsWith(".png") ||
                         ofd.FileName.ToLower().EndsWith(".jpg"))
                {
                    img = new MapWinGIS.Image();
                    img.Open(@ofd.FileName);
                    idxLayerRaster = axMap1.AddLayer(img, true);
                    AddLayer(axMap1.get_LayerName(idxLayerRaster));
                }
            }
        }
        /// <summary>
        /// Will convolve the 2-D filter with the source image, producing the output image.
        /// This overload assumes that you are working with files.
        /// </summary>
        /// <param name="SourceFile">A string representing the image file to open.</param>
        /// <param name="DestFile">A string representing the image file to save to.</param>
        /// <param name="filter">A 2D array of floats, row major.  Filter must be smaller than image.</param>
        /// <param name="ShowProgressDialog">Boolean, true to have the function automatically show a dialog.</param>
        /// <param name="ICallBack">A MapWinGIS.ICallback for handling errors and progress messages</param>
        /// <returns>Boolean, false if the process was canceled.</returns>
        public static bool ApplyFilter(string SourceFile, string DestFile, float[,] filter, bool ShowProgressDialog, MapWinGIS.ICallback ICallBack)
        {
            MapWinUtility.Logger.Dbg("ApplyFilter(SourceFile: " + SourceFile + ",\n" +
                                     "            DestFile: " + DestFile + ",\n" +
                                     "            filter: [" + filter.GetUpperBound(0) + ", " + filter.GetUpperBound(1) + "],\n" +
                                     "            ShowProgressDialog: " + ShowProgressDialog.ToString() + ",\n" +
                                     "            ICallback)");
            bool res;

            // Argument checks
            if (SourceFile == null)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: SourceFile cannot be null.");
                throw new ArgumentException("SourceFile cannot be null.");
            }
            if (System.IO.File.Exists(SourceFile) == false)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: SourceFile not found.");
                throw new ArgumentException("SourceFile not found.");
            }
            if (DestFile == null)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: DestFile cannot be null.");
                throw new ArgumentException("DestFile cannot be null.");
            }
            if (System.IO.File.Exists(SourceFile) == true)
            {
                System.IO.File.Delete(DestFile);
            }
            if (filter.GetUpperBound(0) == 0 || filter.GetUpperBound(1) == 0)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: Filter must have values.");
                throw new ArgumentException("Filter must have values.");
            }

            // Check image object
            MapWinGIS.Image SourceImage = new MapWinGIS.Image();
            res = SourceImage.Open(SourceFile, MapWinGIS.ImageType.USE_FILE_EXTENSION, true, null);
            if (res == false)
            {
                MapWinUtility.Logger.Dbg("Application Exception: " + "Attempting to open " + SourceFile + " produced the following error:\n" + SourceImage.get_ErrorMsg(SourceImage.LastErrorCode));
                throw new ApplicationException("Attempting to open " + SourceFile + " produced the following error:\n" + SourceImage.get_ErrorMsg(SourceImage.LastErrorCode));
            }
            // Try to create the output image
            MapWinGIS.Image DestImage = new MapWinGIS.Image();
            res = DestImage.CreateNew(SourceImage.Width, SourceImage.Height);
            if (res == false)
            {
                MapWinUtility.Logger.Dbg("Application Exception: " + "Attempting to create " + DestFile + " produced the following error:\n" + DestImage.get_ErrorMsg(DestImage.LastErrorCode));
                throw new ApplicationException("Attempting to create " + DestFile + " produced the following error:\n" + DestImage.get_ErrorMsg(DestImage.LastErrorCode));
            }
            DestImage.Save(DestFile, false, MapWinGIS.ImageType.USE_FILE_EXTENSION, ICallBack);
            res = Do_ApplyFilter(SourceImage, ref DestImage, filter, ShowProgressDialog, ICallBack);
            DestImage.Close();
            SourceImage.Close();
            MapWinUtility.Logger.Dbg("Finished ApplyFilter");
            return(res);
        }
Beispiel #7
0
 /// <summary>
 /// 创建一个新的LayerSource类实例
 /// </summary>
 public LayerSource(object obj)
 {
     if (obj is MapWinGIS.Shapefile)
     {
         m_shapefile = obj as MapWinGIS.Shapefile;
     }
     else if (obj is MapWinGIS.Image)
     {
         m_image = obj as MapWinGIS.Image;
     }
     else if (obj is MapWinGIS.Grid)
     {
         m_grid = obj as MapWinGIS.Grid;
     }
 }
Beispiel #8
0
        /****************************/
        public void LayersInfo()
        {
            int pointCount = 0;
            int lineCount  = 0;
            int polyCount  = 0;
            int imgCount   = 0;

            for (int i = 0; i < axMap1.NumLayers; i++)
            {
                object    layer   = axMap1.get_GetObject(axMap1.get_LayerHandle(i));
                Shapefile sf_test = layer as Shapefile;
                if (sf_test != null)
                {
                    switch (sf_test.ShapefileType)
                    {
                    case ShpfileType.SHP_POINT:
                        pointCount++;
                        break;

                    case ShpfileType.SHP_POLYLINE:
                        lineCount++;
                        break;

                    case ShpfileType.SHP_POLYGON:
                        polyCount++;
                        break;
                    }
                }
                else
                {
                    MapWinGIS.Image img = layer as MapWinGIS.Image;
                    if (img != null)
                    {
                        imgCount++;
                    }
                }
            }

            string s = string.Format("Thong tin map:" + Environment.NewLine +
                                     "So Point shapefiles: {0}" + Environment.NewLine +
                                     "So Polyline shapefiles: {1}" + Environment.NewLine +
                                     "So Polygon shapefiles: {2}" + Environment.NewLine +
                                     "So Images: {3}", pointCount, lineCount, polyCount, imgCount);

            MessageBox.Show(s);
        }
Beispiel #9
0
 private void AxMap1_MeasuringChanged(object sender, _DMapEvents_MeasuringChangedEvent e)
 {
     if (e.action == tkMeasuringAction.PointAdded)
     {
     }
     if (e.action == tkMeasuringAction.MesuringStopped)
     {
         if (btnAnotation.Checked)
         {
             Shape shp = new Shape();
             shp.Create(ShpfileType.SHP_POLYGON);
             //shp_tmp.EditAddShape()
             double x, y;
             //Debug.WriteLine("Measured points (in map units.): " + axMap1.Measuring.PointCount);
             for (int i = 0; i < axMap1.Measuring.PointCount; i++)
             {
                 if (axMap1.Measuring.get_PointXY(i, out x, out y))
                 {
                     //var c = 0;
                     MapWinGIS.Point ptn = new MapWinGIS.Point();
                     ptn.Set(x, y);
                     shp.InsertPoint(ptn, ref i);
                     //Debug.WriteLine("x={0}; y={1}", x, y);
                 }
             }
             tmpLayer.EditAddShape(shp);
             axMap1.Redraw();
         }
         if (btnVP.Checked)
         {
             double x, y;
             axMap1.Measuring.get_PointXY(0, out x, out y);
             MapWinGIS.Point pt1 = new Point();
             pt1.Set(x, y);
             axMap1.Measuring.get_PointXY(1, out x, out y);
             MapWinGIS.Point pt2 = new Point();
             pt2.Set(x, y);
             MapWinGIS.Image         DEMImg = axMap1.get_Image(idxLayerRaster);
             Vertical_Profiling_Form vpf    = new Vertical_Profiling_Form(DEMImg, pt1, pt2);
             vpf.Show(this);
             axMap1.Redraw();
         }
     }
 }
Beispiel #10
0
        /// <summary>
        /// 从指定的目录加载一张图片到PreviewMap中
        /// </summary>
        /// <param name="filename">图片的路径</param>
        /// <returns>true 加载成功,false,失败</returns>
        public bool GetPictureFromFile(string filename)
        {
            MapWinGIS.Image img        = new MapWinGIS.Image();
            string          extentName = MapWinGIS.Utility.MiscUtils.GetExtensionName(filename);

            if ((img.CdlgFilter.ToLower()).IndexOf(extentName.ToLower()) > 0)
            {
                if (img.Open(filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false) == false)
                {
                    Program.g_error = "打开文件并加载到Preview Map上失败";
                    return(false);
                }
                else //文件打开
                {
                    string cutExtentName = filename.Substring(0, filename.Length - extentName.Length - 1);
                    string tStr          = Path.GetDirectoryName(cutExtentName + ".*");
                    if (tStr != "")
                    {
                        switch (MapWinGIS.Utility.MiscUtils.GetExtensionName(tStr).ToLower())
                        {
                        case "bpw":     //world类型的图片文件
                        case "gfw":
                            m_ShowLocatorBox = true;
                            break;

                        default:     // 不是一个world类型的文件
                            m_ShowLocatorBox = false;
                            break;
                        }
                    }
                    Program.frmMain.MapPreview.AddLayer(img, true);
                }
            }
            else
            {
                Program.g_error = "不支持的图片格式";
                return(false);
            }
            return(true);
        }
Beispiel #11
0
        //public static double Percentile(double[] elements, double percentile)
        //{
        //    Array.Sort(elements);
        //    double realIndex = percentile * (elements.Length - 1);
        //    int index = (int)realIndex;
        //    double frac = realIndex - index;
        //    if (index + 1 < elements.Length)
        //        return elements[index] * (1 - frac) + elements[index + 1] * frac;
        //    else
        //        return elements[index];
        //}
        private void axMap1_MouseMoveEvent(object sender, AxMapWinGIS._DMapEvents_MouseMoveEvent e)
        {
            if (btnShowCellInfo.Checked)
            {
                string stt = "";
                int    row;
                int    column;
                double X = 0;
                double Y = 0;
                axMap1.PixelToProj(e.x, e.y, ref X, ref Y);
                stt += "Kinh độ: " + Convert.ToString(Math.Round(X, 3)) +
                       " Vĩ độ: " + Convert.ToString(Math.Round(Y, 3)) +
                       ". Giá trị Band: ";
                MapWinGIS.Image img = axMap1.get_Image(idxLayerRaster);
                img.ProjectionToImage(X, Y, out column, out row);
                double[] vals = new double[img.NoBands];
                for (int i = 1; i <= img.NoBands; i++)
                {
                    GdalRasterBand rst = img.get_Band(i);
                    double         pVal;
                    rst.get_Value(row, column, out pVal);
                    vals[i - 1] = pVal;
                    stt        += i.ToString() + " : " + Math.Round(pVal, 3).ToString() + "; ";
                }

                toolStripStatusLabel1.Text = stt;
            }
            else
            {
                double x, y;
                x = y = 0;
                axMap1.PixelToProj(e.x, e.y, ref x, ref y);
                x = Math.Round(x, 3);
                y = Math.Round(y, 3);

                toolStripStatusLabel1.Text = "Kinh độ: " + Convert.ToString(x) + " Vĩ độ: " + Convert.ToString(y);
            }
        }
Beispiel #12
0
        /// <summary>
        /// 关闭图层. 设置未定义的图层类型
        /// </summary>
        public void Close()
        {
            m_error = LayerSourceError.None;
            switch (this.Type)
            {
            case LayerSourceType.Shapefile:
                m_shapefile.Close();
                m_shapefile = null;
                break;

            case LayerSourceType.Image:
                m_image.Close();
                m_image = null;
                break;

            case LayerSourceType.Grid:
                m_grid.Close();
                m_grid = null;
                break;

            default:
                break;
            }
        }
        /// <summary>
        /// Reprojects an image using the currently defined projective transform.
        /// Be sure to call Derive_Coefficients first.  This loops through point by point
        /// so won't be very fast.
        /// </summary>
        /// <param name="SourceImage">A MapWinGIS.Image object to be transformed</param>
        /// <param name="resultImage">A string representing the destination filename</param>
        /// <param name="ICallBack">A MapWinGIS.ICallback interface for progress messages</param>
        /// <remarks>ArgumentExceptions should be trapped for user error, but other types should be reported as bugs</remarks>
        public void ProjectImage(MapWinGIS.Image SourceImage, string resultImage, MapWinGIS.ICallback ICallBack)
        {
            bool res;

            if (SourceImage == null)
            {
                throw new ArgumentException("Source Image cannot be null.");
            }
            if (resultImage == null)
            {
                resultImage = System.IO.Path.ChangeExtension(SourceImage.Filename, "_Projected" + System.IO.Path.GetExtension(SourceImage.Filename));
            }
            if (Defined == false)
            {
                throw new ApplicationException("You first have to define the coefficients by calling Derive_Coefficients.");
            }
            MapWinGIS.Image DestImage = new MapWinGIS.Image();
            try
            {
                res = DestImage.CreateNew(m_OutputWidth, m_OutputHeight);
            }
            catch
            {
                throw new ApplicationException("The current Image object crashes with images too large to fit in memory.");
            }
            if (res == false)
            {
                throw new ApplicationException("Application Exception when Creating New: " + DestImage.get_ErrorMsg(DestImage.LastErrorCode));
            }
            if (res == false)
            {
                throw new ApplicationException("Image object is having trouble creating a new image.");
            }
            for (int Yprj = 0; Yprj < m_OutputHeight; Yprj++)
            {
                for (int Xprj = 0; Xprj < m_OutputWidth; Xprj++)
                {
                    double X, Y;
                    double X1, Y1;
                    int    Xorig = 0;
                    int    Yorig = 0;

                    X1 = (double)Xprj;
                    Y1 = (double)Yprj;
                    X  = -(b * Y1 - Y1 * h * c + e * c - X1 * e + f * X1 * h - f * b) / (X1 * h * d + b * Y1 * g - b * d - X1 * g * e + a * e - a * Y1 * h);
                    Y  = -(c * Y1 * g + X1 * d - a * Y1 - X1 * g * f - c * d + a * f) / (X1 * h * d + b * Y1 * g - b * d - X1 * g * e + a * e - a * Y1 * h);

                    if (X < 0 || Y < 0 || X > m_InputWidth || Y > m_InputHeight)
                    {
                        continue;
                    }
                    // using nearest neighbors
                    Xorig = rnd(X);
                    Yorig = rnd(Y);

                    int Rowo = (m_InputHeight - 1) - Yorig;
                    int pVal = SourceImage.get_Value(Rowo, Xorig);

                    int row = (m_OutputHeight - 1) - Yprj;
                    DestImage.set_Value(row, Xprj, pVal);
                }
                if (ICallBack != null)
                {
                    ICallBack.Progress("Status", (Yprj * 100) / m_OutputHeight, "Row: " + Yprj.ToString());
                }
            }

            DestImage.dX        = m_OutputCellWidth;
            DestImage.dY        = m_OutputCellHeight;
            DestImage.XllCenter = m_XllCenter;
            DestImage.YllCenter = m_YllCenter;
            string dir = System.IO.Path.GetDirectoryName(resultImage);

            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            if (System.IO.Path.GetExtension(resultImage) == ".jpg")
            {
                resultImage = System.IO.Path.ChangeExtension(resultImage, ".bmp");
            }
            res = DestImage.Save(resultImage, true, MapWinGIS.ImageType.USE_FILE_EXTENSION, ICallBack);
            if (res == false)
            {
                throw new ApplicationException(DestImage.get_ErrorMsg(DestImage.LastErrorCode));
            }
            DestImage.SetProjection(SourceImage.GetProjection());
            DestImage.Close();
            if (ICallBack != null)
            {
                ICallBack.Progress("Status", 0, "Saved output as " + DestImage.Filename);
            }
        }
Beispiel #14
0
        /// <summary>
        /// 更新PreviewMap的地图显示
        /// </summary>
        /// <param name="fullExtents">指示是否使用全图显示地图</param>
        public void GetPictureFromMap(bool fullExtents)
        {
            try
            {
                MapWinGIS.Extents exts;
                MapWinGIS.Image   img     = new MapWinGIS.Image();
                double            ratio   = 0;
                MapWinGIS.Extents oldExts = (MapWinGIS.Extents)Program.frmMain.MapMain.Extents;

                //锁定地图
                Program.frmMain.MapPreview.LockWindow(MapWinGIS.tkLockMode.lmLock);
                Program.frmMain.MapMain.LockWindow(MapWinGIS.tkLockMode.lmLock);

                if (fullExtents) //更新为全图显示,主地图也更新为全图显示
                {
                    exts = Program.frmMain.m_View.MaxVisibleExtents;
                    if (Program.frmMain.MapPreview.Width < Program.frmMain.MapPreview.Height) //宽小于高
                    {
                        ratio = System.Convert.ToDouble(Program.frmMain.MapPreview.Width / Program.frmMain.MapMain.Width);
                    }
                    else //宽大于高
                    {
                        ratio = System.Convert.ToDouble(Program.frmMain.MapPreview.Height / Program.frmMain.MapMain.Height);
                    }
                    ratio *= 1.5; //缩放比例

                    Program.frmMain.MapMain.Extents = exts;
                    exts = (MapWinGIS.Extents)Program.frmMain.MapMain.Extents;
                }
                else
                {
                    exts = (MapWinGIS.Extents)Program.frmMain.MapMain.Extents;
                }

                img = (MapWinGIS.Image)(Program.frmMain.MapMain.SnapShot(exts));

                MapWinGIS.Utility.ImageUtils cvter  = new MapWinGIS.Utility.ImageUtils();
                System.Drawing.Image         tmpImg = MapWinGIS.Utility.ImageUtils.ObjectToImage(img.Picture, System.Convert.ToInt32(img.Width * ratio), System.Convert.ToInt32(img.Height * ratio));

                img.Picture          = (stdole.IPictureDisp)(cvter.ImageToIPictureDisp(tmpImg));
                img.dX               = (exts.xMax - exts.xMin) / img.Width;
                img.dY               = (exts.yMax - exts.yMin) / img.Height;
                img.XllCenter        = exts.xMin + 0.5 * img.dX;
                img.YllCenter        = exts.yMin + 0.5 * img.dX;
                img.DownsamplingMode = MapWinGIS.tkInterpolationMode.imHighQualityBicubic;
                img.UpsamplingMode   = MapWinGIS.tkInterpolationMode.imHighQualityBicubic;

                Program.frmMain.MapPreview.RemoveAllLayers();
                Program.frmMain.MapPreview.AddLayer(img, true);
                Program.frmMain.MapPreview.ExtentPad = 0;
                Program.frmMain.MapPreview.ZoomToMaxExtents();
                Program.frmMain.m_PreviewMap.m_ShowLocatorBox = true;
                Program.frmMain.m_PreviewMap.UpdateLocatorBox();

                Program.frmMain.mnuZoomPreviewMap.Enabled = Program.frmMain.MapMain.NumLayers > 0 && Program.frmMain.PreviewMapExtentsValid();
                if (Program.frmMain.m_Menu["mnuZoomToPreviewExtents"] != null)
                {
                    Program.frmMain.m_Menu["mnuZoomToPreviewExtents"].Enabled = Program.frmMain.MapMain.NumLayers > 0 && Program.frmMain.PreviewMapExtentsValid();
                }
            }
            catch (Exception ex)
            {
                Program.g_error = ex.ToString();
                Program.ShowError(ex);
            }
            finally
            {
                //解锁地图
                Program.frmMain.MapPreview.LockWindow(MapWinGIS.tkLockMode.lmUnlock);
                Program.frmMain.MapMain.LockWindow(MapWinGIS.tkLockMode.lmUnlock);
            }
        }
Beispiel #15
0
        /// <summary>
        /// 将图层颜色设置输出到一个指定路径
        /// </summary>
        public static bool ExportScheme(Interfaces.Layer lyr, string path)
        {
            XmlDocument  doc = new XmlDocument();
            XmlElement   mainScheme;
            XmlElement   root;
            XmlAttribute schemeType;

            root = doc.CreateElement("ColoringScheme");

            if (lyr == null)
            {
                return(false);
            }

            if (lyr.LayerType == Interfaces.eLayerType.LineShapefile || lyr.LayerType == Interfaces.eLayerType.PointShapefile || lyr.LayerType == Interfaces.eLayerType.PolygonShapefile)
            {
                MapWinGIS.ShapefileColorScheme sch = (MapWinGIS.ShapefileColorScheme)lyr.ColoringScheme;
                MapWinGIS.Shapefile            sf  = (MapWinGIS.Shapefile)lyr.GetObject();
                XmlAttribute fldName;
                XmlAttribute key;

                if (sch == null || sch.NumBreaks() == 0)
                {
                    return(false);
                }
                schemeType           = doc.CreateAttribute("SchemeType");
                schemeType.InnerText = "Shapefile";
                root.Attributes.Append(schemeType);
                mainScheme        = doc.CreateElement("ShapefileColoringScheme");
                fldName           = doc.CreateAttribute("FieldName");
                key               = doc.CreateAttribute("Key");
                fldName.InnerText = sf.Field[sch.FieldIndex].Name;
                key.InnerText     = sch.Key;

                mainScheme.Attributes.Append(fldName);
                mainScheme.Attributes.Append(key);
                root.AppendChild(mainScheme);
                doc.AppendChild(root);
                if (ExportScheme(((MapWinGIS.ShapefileColorScheme)lyr.ColoringScheme), doc, mainScheme))
                {
                    doc.Save(path);
                    return(true);
                }
                else
                {
                    MapWinGIS.Utility.Logger.Message("导出 coloring scheme 失败.", "错误");
                    return(false);
                }
            }
            else if (lyr.LayerType == Interfaces.eLayerType.Grid)
            {
                MapWinGIS.GridColorScheme sch = (MapWinGIS.GridColorScheme)lyr.ColoringScheme;
                MapWinGIS.Grid            grd = lyr.GetGridObject;
                XmlAttribute AmbientIntensity;
                XmlAttribute Key;
                XmlAttribute LightSourceAzimuth;
                XmlAttribute LightSourceElevation;
                XmlAttribute LightSourceIntensity;
                XmlAttribute NoDataColor;
                XmlAttribute GridName;
                XmlAttribute GroupName;
                XmlAttribute ImageLayerFillTransparency;
                XmlAttribute ImageUpsamplingMethod;
                XmlAttribute ImageDownsamplingMethod;

                if (sch == null || sch.NumBreaks == 0)
                {
                    return(false);
                }
                GridName             = doc.CreateAttribute("GridName");
                GroupName            = doc.CreateAttribute("GroupName");
                schemeType           = doc.CreateAttribute("SchemeType");
                schemeType.InnerText = "Grid";
                root.Attributes.Append(schemeType);

                AmbientIntensity = doc.CreateAttribute("AmbientIntensity");
                Key = doc.CreateAttribute("Key");
                LightSourceAzimuth         = doc.CreateAttribute("LightSourceAzimuth");
                LightSourceElevation       = doc.CreateAttribute("LightSourceElevation");
                LightSourceIntensity       = doc.CreateAttribute("LightSourceIntensity");
                ImageLayerFillTransparency = doc.CreateAttribute("ImageLayerFillTransparency");
                ImageUpsamplingMethod      = doc.CreateAttribute("ImageUpsamplingMethod");
                ImageDownsamplingMethod    = doc.CreateAttribute("ImageDownsamplingMethod");

                NoDataColor                          = doc.CreateAttribute("NoDataColor");
                GridName.InnerText                   = lyr.Name;
                GroupName.InnerText                  = Program.frmMain.Legend.Groups.ItemByHandle(lyr.GroupHandle).Text;
                AmbientIntensity.InnerText           = (sch.AmbientIntensity).ToString();
                Key.InnerText                        = sch.Key;
                LightSourceAzimuth.InnerText         = (sch.LightSourceAzimuth).ToString();
                LightSourceElevation.InnerText       = (sch.LightSourceElevation).ToString();
                LightSourceIntensity.InnerText       = (sch.LightSourceIntensity).ToString();
                NoDataColor.InnerText                = (ColorScheme.UIntToColor(sch.NoDataColor).ToArgb()).ToString();
                ImageLayerFillTransparency.InnerText = ((System.Convert.ToInt32(lyr.ImageLayerFillTransparency * 100)) / 100).ToString();

                MapWinGIS.Image img = new MapWinGIS.Image();
                img = (MapWinGIS.Image)(Program.frmMain.MapMain.get_GetObject(lyr.Handle));
                if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imBicubic)
                {
                    ImageDownsamplingMethod.InnerText = "Bicubic";
                }
                else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imBilinear)
                {
                    ImageDownsamplingMethod.InnerText = "Bilinear";
                }
                else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBicubic)
                {
                    ImageDownsamplingMethod.InnerText = "HighQualityBicubic";
                }
                else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBilinear)
                {
                    ImageDownsamplingMethod.InnerText = "HighQualityBilinear";
                }
                else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imNone)
                {
                    ImageDownsamplingMethod.InnerText = "None";
                }
                else
                {
                    ImageDownsamplingMethod.InnerText = "None";
                }

                if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imBicubic)
                {
                    ImageUpsamplingMethod.InnerText = "Bicubic";
                }
                else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imBilinear)
                {
                    ImageUpsamplingMethod.InnerText = "Bilinear";
                }
                else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBicubic)
                {
                    ImageUpsamplingMethod.InnerText = "HighQualityBicubic";
                }
                else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBilinear)
                {
                    ImageUpsamplingMethod.InnerText = "HighQualityBilinear";
                }
                else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imNone)
                {
                    ImageUpsamplingMethod.InnerText = "None";
                }
                else
                {
                    ImageUpsamplingMethod.InnerText = "None";
                }

                mainScheme = doc.CreateElement("GridColoringScheme");
                mainScheme.Attributes.Append(AmbientIntensity);
                mainScheme.Attributes.Append(Key);
                mainScheme.Attributes.Append(LightSourceAzimuth);
                mainScheme.Attributes.Append(LightSourceElevation);
                mainScheme.Attributes.Append(LightSourceIntensity);
                mainScheme.Attributes.Append(NoDataColor);
                mainScheme.Attributes.Append(ImageLayerFillTransparency);
                mainScheme.Attributes.Append(ImageUpsamplingMethod);
                mainScheme.Attributes.Append(ImageDownsamplingMethod);

                root.AppendChild(mainScheme);
                root.Attributes.Append(GridName);
                root.Attributes.Append(GroupName);
                doc.AppendChild(root);
                if (ExportScheme(((MapWinGIS.GridColorScheme)lyr.ColoringScheme), doc, mainScheme))
                {
                    doc.Save(path);
                    return(true);
                }
                else
                {
                    MapWinGIS.Utility.Logger.Message("导出 coloring scheme 失败.", "错误");
                    return(false);
                }
            }
            return(false);
        }
Beispiel #16
0
        private void AddLayer()
        {
            MapWinGIS.Shapefile shpfileOpen;
            string[] fileNombres;

            MapWinGIS.Grid grid;
            MapWinGIS.GridColorScheme gridScheme;
            MapWinGIS.Image image;
            MapWinGIS.Utils utils;

            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Multiselect = true;

            int handle;
            string ext;

            //initialize dialog
            openDlg.Filter = "Supported Formats|*.shp;*.bgd;*asc;*.jpg|Shapefile (*.shp)|*.shp|Binary Grids (*.bgd)|*.bgd|ASCII Grids (*.asc)|*.asc |World File (*.jpg)|*.jpg";
            openDlg.CheckFileExists = true;

            if (openDlg.ShowDialog(this) == DialogResult.OK)
            {
                fileNombres = openDlg.FileNames;
                int totalNombres = fileNombres.Length;
                for (int j = 0; j < totalNombres; j++)
                {

                    //get the extension of the file
                    ext = System.IO.Path.GetExtension(openDlg.FileNames[j]);

                    if (ext == ".bgd" || ext == ".asc" || ext == ".jpg")
                    {
                        if (ext == ".jpg")
                        {
                            image = new MapWinGIS.Image();

                            // open image world file
                            image.Open(openDlg.FileNames[j], MapWinGIS.ImageType.JPEG_FILE, true, null);
                            handle = legend1.Layers.Add(image, true);
                            legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(image.Filename));
                            //handle = axMap1.AddLayer(image, true);
                            handleMap.Add(handle);

                        }
                        else
                        {

                            utils = new MapWinGIS.UtilsClass();
                            gridScheme = new MapWinGIS.GridColorScheme();
                            grid = new MapWinGIS.GridClass();

                            //open the grid
                            grid.Open(openDlg.FileName, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null);

                            //create a coloring scheme for the image
                            gridScheme.UsePredefined(System.Convert.ToDouble(grid.Minimum), System.Convert.ToDouble(grid.Maximum), MapWinGIS.PredefinedColorScheme.SummerMountains);

                            //convert the grid to a image
                            image = utils.GridToImage(grid, gridScheme, null);

                            //add the image to the legend and map
                            handle = axMap1.AddLayer(image, true);
                            handleMap.Add(handle);

                            grid.Close();

                            //utils = new MapWinGIS.UtilsClass();
                            //gridScheme = new MapWinGIS.GridColorScheme();
                            //grid = new MapWinGIS.GridClass();

                            ////open the grid
                            //grid.Open(openDlg.FileName, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null);

                            ////create a coloring scheme for the image
                            //gridScheme.UsePredefined(System.Convert.ToDouble(grid.Minimum), System.Convert.ToDouble(grid.Maximum), MapWinGIS.PredefinedColorScheme.SummerMountains);

                            ////convert the grid to a image
                            //image = utils.GridToImage(grid, gridScheme, null);

                            ////add the image to the legend and map
                            //handle = axMap1.AddLayer(image, true);
                            ////handle = legend1.Layers.Add(image, true);

                            //if (legend1.Layers.IsValidHandle(handle))
                            //{
                            //    //set the layer name
                            //    legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(grid.Filename));

                            //    //set's the legend layer type, this displays a default icon in the legend (line shapefile, point shapefile,polygon shapefile,grid,image)
                            //    legend1.Layers.ItemByHandle(handle).Type = MapWindow.Interfaces.eLayerType.Grid;

                            //    //set coloring scheme
                            //    //when applying a coloring scheme to a shapfile use axMap1.ApplyLegendColors(ShapefileColorScheme)
                            //    //when applying a coloring scheme for a grid or image use axMap1.SetImageLayerColorScheme(handle,GridColorScheme);
                            //    axMap1.SetImageLayerColorScheme(legend1.SelectedLayer, gridScheme);
                            //    legend1.Layers.ItemByHandle(legend1.SelectedLayer).Refresh();
                            //}

                            //close the grid
                            //grid.Close();
                        }

                    }
                    else if (ext == ".shp")
                    {
                        shpfileOpen = new MapWinGIS.ShapefileClass();

                        //open the shapefile
                        shpfileOpen.Open(openDlg.FileNames[j], null);

                        //add the shapefile to the map and legend
                        handle = legend1.Layers.Add(shpfileOpen, true);
                        legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(shpfileOpen.Filename));
                        //handle = axMap1.AddLayer(shpfileOpen, true);
                        handleMap.Add(handle);
                        string oldProj = shpfileOpen.Projection;

                        // bool status = MapWinGeoProc.SpatialReference.ProjectShapefile(sourceProj, destProj, inputSF, resultSF)
                        this.flagMapaAbierto = true;

                    }
                }

            }
        }
        /// <summary>
        /// Draws picture in the legend. Picture can be either an image or an icon
        /// </summary>
        protected void DrawPicture(Graphics g, int picLeft, int picTop, int picWidth, int picHeight, object picture)
        {
            if (picture == null)
            {
                return;
            }

            var oldSm = g.SmoothingMode;

            g.SmoothingMode = SmoothingMode.HighQuality;

            var rect = new Rectangle(picLeft, picTop, picWidth, picHeight);

            var icon = picture as Icon;

            if (icon != null)
            {
                g.DrawIcon(icon, rect);
            }
            else
            {
                // try casting it to an Image
                Image img = null;
                try
                {
                    img = (Image)picture;
                }
                catch (InvalidCastException)
                {
                }

                if (img != null)
                {
                    g.DrawImage(img, rect);
                }
                else
                {
                    MapWinGIS.Image mwImg = null;
                    try
                    {
                        mwImg = (MapWinGIS.Image)picture;
                    }
                    catch (InvalidCastException)
                    {
                    }

                    if (mwImg != null)
                    {
                        try
                        {
                            img = Image.FromHbitmap(new IntPtr(mwImg.Picture.Handle));
                            g.DrawImage(img, rect);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            g.SmoothingMode = oldSm;
        }
        // False if the user canceled, true otherwise
        private static bool Do_ApplyFilter(MapWinGIS.Image SourceImage, ref MapWinGIS.Image DestImage, float[,] filter, bool ShowProgressDialog, MapWinGIS.ICallback ICallBack)
        {
            int Prog    = 0;
            int OldProg = 0;


            // Report unnamed as differently from null
            string SourceFile = "null";
            string DestFile   = "null";

            if (SourceImage != null)
            {
                SourceFile = SourceImage.Filename;
                if (SourceFile == null)
                {
                    SourceFile = "Unnamed";
                }
            }
            else
            {
                MapWinUtility.Logger.Dbg("Argument Exception: SourceImage cannot be null.");
                throw new ArgumentException("SourceImage cannot be null.");
            }
            if (DestImage != null)
            {
                DestFile = SourceImage.Filename;
                if (DestFile == null)
                {
                    DestFile = "Unnamed";
                }
            }
            else
            {
                MapWinUtility.Logger.Dbg("Argument Exception: DestImage cannot be null.");
                throw new ArgumentException("DestImage cannot be null.");
            }

            MapWinUtility.Logger.Dbg("Do_ApplyFilter(SourceImage: " + SourceImage.Filename + ",\n" +
                                     "            DestImage: " + DestImage.Filename + ",\n" +
                                     "            filter: [" + filter.GetUpperBound(0) + ", " + filter.GetUpperBound(1) + "],\n" +
                                     "            ShowProgressDialog: " + ShowProgressDialog.ToString() + ",\n" +
                                     "            ICallback)");

            ProgressDialog MyProgress = new ProgressDialog();


            if (filter.GetUpperBound(0) == 0 || filter.GetUpperBound(1) == 0)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: Filter must have values.");
                throw new ArgumentException("Filter must have values.");
            }

            // Ensure the filter is smaller than the image.
            if (filter.GetUpperBound(0) > SourceImage.Height || filter.GetUpperBound(1) > SourceImage.Width)
            {
                throw new ArgumentException("The filter is too large for this image.  In order for convolution to work, the image must be larger than the filter.");
            }

            // We are going to assume mirror handling of edges
            ExtHandler LocHandler = new ExtHandler(SourceImage.Height, SourceImage.Width);

            // convolve
            int R, G, B, color;
            int Xcor = 0, Ycor = 0; // Corrected X and Y locations to take into account mirror
            int fH, fW;             // stores the values of half the height and width of the filter

            fH = (int)filter.GetUpperBound(0) / 2;
            fW = (int)filter.GetUpperBound(1) / 2;

            if (ICallBack == null)
            {
                MyProgress.Show();
                MyProgress.WriteMessage("Applying Filter...");
                MapWinUtility.Logger.Progress("Applying Filter...", Prog, OldProg);
            }
            for (int row = 0; row < SourceImage.Height; row++)
            {
                for (int col = 0; col < SourceImage.Width; col++)
                {
                    float fR = 0;
                    float fG = 0;
                    float fB = 0;

                    for (int Y = 0; Y <= filter.GetUpperBound(0); Y++)
                    {
                        for (int X = 0; X <= filter.GetUpperBound(1); X++)
                        {
                            // Read the color for this spot
                            LocHandler.CorrectLocation(col + X - fW, row + Y - fH, ref Xcor, ref Ycor);
                            color = SourceImage.get_Value(Ycor, Xcor);
                            R     = color % 256;
                            G     = (int)(color / 256) % 256;
                            B     = (int)(color / (256 * 256));

                            // convolve the values with the filter and add them to the accumulators
                            fR += filter[Y, X] * R;
                            fG += filter[Y, X] * G;
                            fB += filter[Y, X] * B;
                        }
                    }
                    // After convolution, write the combined value to the file
                    R = (int)fR;
                    if (R > 255)
                    {
                        R = 255;
                    }
                    G = (int)fG;
                    if (G > 255)
                    {
                        G = 255;
                    }
                    B = (int)fB;
                    if (B > 255)
                    {
                        B = 255;
                    }
                    color = (256 * 256) * B + 256 * G + R;
                    DestImage.set_Value(row, col, color);
                }
                Prog = (100 * row) / SourceImage.Height;
                if (Prog > OldProg)
                {
                    if (ICallBack != null)
                    {
                        ICallBack.Progress("Status", Prog, "Filtering Image...");
                    }


                    if (ShowProgressDialog == true)
                    {
                        MyProgress.Progress = Prog;

                        if (MyProgress.IsCanceled == true)
                        {
                            MapWinUtility.Logger.Message("Apply Filter was canceled.", "Process Canceled", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.DialogResult.OK);
                            return(false);
                        }
                    }

                    MapWinUtility.Logger.Progress("Filtering Image..." + Prog.ToString() + "%Complete", Prog, OldProg);
                    OldProg = Prog;
                }
            }
            MyProgress.Hide();
            DestImage.dX = SourceImage.dX;
            DestImage.dY = SourceImage.dY;
            DestImage.SetProjection(SourceImage.GetProjection());
            DestImage.Save(DestImage.Filename, true, MapWinGIS.ImageType.USE_FILE_EXTENSION, null);
            MapWinUtility.Logger.Dbg("Finsihed ApplyFilter");
            return(true);
        }
        /// <summary>
        /// 反序列化点图像
        /// 从mwsr中获得点信息并翻译,应用到图层上。
        /// </summary>
        public void DeserializePointImageScheme(int newHandle, XmlElement root)
        {
            Program.frmMain.MapMain.LockWindow(MapWinGIS.tkLockMode.lmLock);
            try
            {
                MapWinGIS.Utility.ImageUtils imgUtil = new MapWinGIS.Utility.ImageUtils();

                bool found = false;
                Interfaces.ShapefilePointImageScheme csh = new Interfaces.ShapefilePointImageScheme(newHandle);

                Hashtable TranslationTable = new Hashtable();

                foreach (XmlElement xe1 in root)
                {
                    if (xe1.Name == "PointImageScheme")
                    {
                        found          = true;
                        csh.FieldIndex = long.Parse(xe1.Attributes["FieldIndex"].InnerText);

                        foreach (XmlElement xe2 in xe1.ChildNodes)
                        {
                            if (xe2.Name == "ImageData")
                            {
                                foreach (XmlElement xe3 in xe2.ChildNodes)
                                {
                                    long origIndex = long.Parse(xe3.Attributes["ID"].InnerText);

                                    string imgtype;
                                    imgtype = xe3["Image"].Attributes["Type"].InnerText;
                                    System.Drawing.Image img = (System.Drawing.Image)(ConvertStringToImage(xe3["Image"].InnerText, imgtype));

                                    MapWinGIS.Image ico = new MapWinGIS.Image();
                                    ico.Picture = (stdole.IPictureDisp)imgUtil.ImageToIPictureDisp(img);
                                    if (ico != null)
                                    {
                                        ico.TransparencyColor = (uint)ico.Value[0, 0];
                                    }

                                    int newidx = System.Convert.ToInt32(Program.frmMain.MapMain.set_UDPointImageListAdd(newHandle, ico));
                                    TranslationTable.Add(origIndex, newidx);
                                    img = null;
                                }
                            }
                            else if (xe2.Name == "ItemData")
                            {
                                foreach (XmlElement xe3 in xe2.ChildNodes)
                                {
                                    if (xe3.Name == "Item")
                                    {
                                        string tag         = xe3.Attributes["MatchValue"].InnerText;
                                        long   imgIndex    = long.Parse(xe3.Attributes["ImgIndex"].InnerText);
                                        long   actualIndex = -1;
                                        if (TranslationTable.Contains(imgIndex))
                                        {
                                            actualIndex = System.Convert.ToInt64(TranslationTable[imgIndex]);
                                        }
                                        else
                                        {
                                            actualIndex = imgIndex;
                                        }

                                        if (actualIndex != -1 && tag != "")
                                        {
                                            csh.Items.Add(tag, actualIndex);
                                        }

                                        MapWinGIS.Shapefile sf;

                                        sf = (MapWinGIS.Shapefile)(Program.frmMain.m_Layers[newHandle].GetObject());
                                        if (sf == null)
                                        {
                                            Program.g_error = "获取Shapefile 对象失败。";
                                            return;
                                        }

                                        if (actualIndex != -1)
                                        {
                                            for (int j = 0; j < sf.NumShapes; j++)
                                            {
                                                if (sf.CellValue[(int)csh.FieldIndex, j].ToString() == tag)
                                                {
                                                    Program.frmMain.MapMain.set_ShapePointImageListID(newHandle, j, (int)actualIndex);
                                                    if (Program.frmMain.MapMain.get_ShapePointType(newHandle, j) != MapWinGIS.tkPointType.ptImageList)
                                                    {
                                                        Program.frmMain.MapMain.set_ShapePointType(newHandle, j, MapWinGIS.tkPointType.ptImageList);
                                                    }
                                                    Program.frmMain.MapMain.set_ShapePointSize(newHandle, j, 1);
                                                }
                                            }
                                        }

                                        sf = null;
                                    }
                                }
                            }
                            else if (xe2.Name == "ItemVisibility")
                            {
                                foreach (XmlElement xe3 in xe2.ChildNodes)
                                {
                                    if (xe3.Name == "Item")
                                    {
                                        string tag = xe3.Attributes["MatchValue"].InnerText;
                                        bool   vis = bool.Parse(xe3.Attributes["Visible"].InnerText);
                                        csh.ItemVisibility.Add(tag, vis);

                                        MapWinGIS.Shapefile sf;

                                        sf = (MapWinGIS.Shapefile)(Program.frmMain.m_Layers[newHandle].GetObject());
                                        if (sf == null)
                                        {
                                            Program.g_error = "获取Shapefile 对象失败.";
                                            return;
                                        }

                                        for (int j = 0; j < sf.NumShapes; j++)
                                        {
                                            if (sf.CellValue[(int)csh.FieldIndex, j].ToString() == tag)
                                            {
                                                Program.frmMain.MapMain.set_ShapeVisible(newHandle, j, vis);
                                            }
                                        }

                                        sf = null;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }

                if (found)
                {
                    Program.frmMain.Legend.Layers.ItemByHandle(newHandle).PointImageScheme = csh;
                }

                TranslationTable.Clear();
                GC.Collect();
            }
            catch (Exception ex)
            {
                MapWinGIS.Utility.Logger.Dbg("DEBUG: " + ex.ToString());
            }
            finally
            {
                Program.frmMain.MapMain.LockWindow(MapWinGIS.tkLockMode.lmUnlock);
            }
        }
Beispiel #20
0
 /// <summary>
 /// 创建一个新的LayerSource类实例(Image)
 /// </summary>
 public LayerSource(MapWinGIS.Image image)
 {
     m_image = image;
 }
Beispiel #21
0
        private void Map(Round t)
        {
            AxMapWinGIS.AxMap map = new AxMapWinGIS.AxMap();
            map.Width  = 380;
            map.Height = 380;
            host.Child = map;
            map.Show();
            map.CreateControl();
            map.ShowZoomBar     = false;
            map.ShowCoordinates = MapWinGIS.tkCoordinatesDisplay.cdmNone;
            map.CursorMode      = MapWinGIS.tkCursorMode.cmNone;

            MapWinGIS.Shapefile shapeFileMap = new MapWinGIS.Shapefile();
            shapeFileMap.Open(@"D:\Projets\TheManager\TheManager_GUI\bin\Debug\gis\world\World_Countries.shp", null);
            map.AddLayer(shapeFileMap, true);
            ILocalisation localisation = Session.Instance.Game.kernel.LocalisationTournament(t.Tournament);
            double        logoSize     = 30.0;

            if (localisation as Country != null)
            {
                map.ZoomToShape(0, (localisation as Country).ShapeNumber);
            }
            else
            {
                if (localisation.Name() == "Europe")
                {
                    map.ZoomToShape(0, 68 /*12 101*/);
                    map.CurrentZoom = 4;
                }
                else if (localisation.Name() == "Africa")
                {
                    map.ZoomToShape(0, 40);
                    map.CurrentZoom = 3;
                }
                logoSize = 15.0;
            }

            foreach (Club c in t.clubs)
            {
                CityClub cc = c as CityClub;
                if (cc != null)
                {
                    double projX = -1;
                    double projY = -1;
                    map.DegreesToProj(cc.city.Position.Longitude, cc.city.Position.Latitude, ref projX, ref projY);

                    MapWinGIS.Image img = new MapWinGIS.Image();
                    img.Open(Utils.Logo(c));

                    MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                    sf.CreateNew("", MapWinGIS.ShpfileType.SHP_POINT);
                    sf.DefaultDrawingOptions.AlignPictureByBottom = false;
                    sf.DefaultDrawingOptions.PointType            = MapWinGIS.tkPointSymbolType.ptSymbolPicture;
                    sf.DefaultDrawingOptions.Picture       = img;
                    sf.DefaultDrawingOptions.PictureScaleX = Math.Round(logoSize / img.OriginalWidth, 2);
                    sf.DefaultDrawingOptions.PictureScaleY = Math.Round(logoSize / img.OriginalHeight, 2);
                    sf.CollisionMode = MapWinGIS.tkCollisionMode.AllowCollisions;

                    MapWinGIS.Shape shp = new MapWinGIS.Shape();
                    shp.Create(MapWinGIS.ShpfileType.SHP_POINT);
                    shp.AddPoint(projX, projY);
                    sf.EditAddShape(shp);

                    map.AddLayer(sf, true);
                }
            }
            if (_competition.rounds[_indexTour].clubs.Count > 0 && _competition.rounds[_indexTour].clubs[0] as NationalTeam != null)
            {
                shapeFileMap.StartEditingTable();
                int fieldIndex = shapeFileMap.EditAddField("Qualification", MapWinGIS.FieldType.INTEGER_FIELD, 1, 1);
                shapeFileMap.DefaultDrawingOptions.FillType = MapWinGIS.tkFillType.ftStandard;
                for (int i = 0; i < shapeFileMap.NumShapes; i++)
                {
                    shapeFileMap.EditCellValue(fieldIndex, i, 0);
                }
                Dictionary <NationalTeam, int> clubCourses = new Dictionary <NationalTeam, int>();
                for (int i = 0; i < _competition.rounds.Count; i++)
                {
                    Round round = _competition.rounds[i];
                    foreach (Club c in round.clubs)
                    {
                        NationalTeam nt = c as NationalTeam;
                        if (!clubCourses.ContainsKey(nt))
                        {
                            clubCourses.Add(nt, 1);
                        }
                        clubCourses[nt] = i + 1;
                    }
                }
                foreach (KeyValuePair <NationalTeam, int> kvp in clubCourses)
                {
                    shapeFileMap.EditCellValue(fieldIndex, kvp.Key.country.ShapeNumber, kvp.Value);
                }
                shapeFileMap.Categories.Generate(fieldIndex, MapWinGIS.tkClassificationType.ctUniqueValues, _competition.rounds.Count + 1);
                shapeFileMap.Categories.ApplyExpressions();
                MapWinGIS.ColorScheme colorScheme = new MapWinGIS.ColorScheme();
                colorScheme.SetColors2(MapWinGIS.tkMapColor.AliceBlue, MapWinGIS.tkMapColor.DarkBlue);
                shapeFileMap.Categories.ApplyColorScheme(MapWinGIS.tkColorSchemeType.ctSchemeGraduated, colorScheme);
            }
            map.Redraw();
        }
Beispiel #22
0
        /// <summary>
        /// 打开指定数据源的图层
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public bool Open(string filename, MapWinGIS.ICallback callback)
        {
            this.Close();

            if (filename.ToLower().EndsWith(".shp"))
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(filename, callback))
                {
                    // 检查dbf是否存在
                    bool error = false;
                    if (!File.Exists(Path.ChangeExtension(sf.Filename, ".dbf")))
                    {
                        m_error = LayerSourceError.DbfIsMissing;
                        error   = true;
                    }

                    // 检查DBF记录数相匹配的形状的数量。
                    MapWinGIS.Table table = new MapWinGIS.Table();
                    table.Open(Path.ChangeExtension(sf.Filename, ".dbf"), null);
                    if (sf.NumShapes != table.NumRows)
                    {
                        m_error = LayerSourceError.DbfRecordCountMismatch;
                        error   = true;
                    }

                    table.Close();

                    if (error)
                    {
                        sf.Close();
                    }
                    else
                    {
                        m_shapefile = sf;
                    }
                    return(!error);
                }
                else
                {
                    m_error       = LayerSourceError.OcxBased;
                    m_ErrorString = sf.get_ErrorMsg(sf.LastErrorCode);
                }
            }
            else
            {
                bool asGrid = true;
                if (filename.ToLower().EndsWith(".tif"))
                {
                    asGrid = false;
                }

                // TODO: 可能更聪明的选择是在grid/image中使用应用程序设置
                if (asGrid)
                {
                    MapWinGIS.Grid grid = new MapWinGIS.Grid();
                    if (grid.Open(filename, MapWinGIS.GridDataType.UnknownDataType, false, MapWinGIS.GridFileType.UseExtension, callback))
                    {
                        m_grid = grid;
                        return(true);
                    }
                }

                // 尝试image
                MapWinGIS.Image image = new MapWinGIS.Image();
                if (image.Open(filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, callback))
                {
                    m_image = image;
                    return(true);
                }
                else
                {
                    m_error       = LayerSourceError.OcxBased;
                    m_ErrorString = image.get_ErrorMsg(image.LastErrorCode);
                }
            }
            return(false);
        }