/// <summary>
        /// This draws to the back buffer.  If the Backbuffer doesn't exist, this will create one.
        /// This will not flip the back buffer to the front.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="regions"></param>
        /// <param name="clipRectangles"></param>
        private void DrawWindows(MapArgs args, IList<IEnvelope> regions, IList<Rectangle> clipRectangles)
        {
            Graphics g = args.Device;
            int numBounds = Math.Min(regions.Count, clipRectangles.Count);

            for (int i = 0; i < numBounds; i++)
            {
                Bitmap bmp = DataSet.GetBitmap(regions[i], clipRectangles[i].Size);
                if (bmp != null) g.DrawImage(bmp, clipRectangles[i]);
            }
            if (args.Device == null) g.Dispose();
        }
 /// <summary>
 /// This will draw any features that intersect this region.  To specify the features
 /// directly, use OnDrawFeatures.  This will not clear existing buffer content.
 /// For that call Initialize instead.
 /// </summary>
 /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
 /// <param name="regions">The geographic regions to draw</param>
 /// <returns>The list of rectangular areas that match the specified regions</returns>
 public void DrawRegions(MapArgs args, List<IEnvelope> regions)
 {
     List<Rectangle> clipRects = args.ProjToPixel(regions);
     DrawWindows(args, regions, clipRects);
 }
Exemplo n.º 3
0
 private Task <MapCoordinates> MapOnImplementationAsync(MapArgs args)
 {
     return(Task.FromResult(args.Coordinates));
 }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a new raster with the specified cell size.  If the cell size
        /// is zero, this will default to the shorter of the width or height
        /// divided by 256.  If the cell size produces a raster that is greater
        /// than 8, 000 pixels in either dimension, it will be re-sized to
        /// create an 8, 000 length or width raster.
        /// </summary>
        /// <param name="fs">The featureset to convert to a raster.</param>
        /// <param name="extent">Force the raster to this specified extent.</param>
        /// <param name="cellSize">The double extent of the cell.</param>
        /// <param name="fieldName">The integer field index of the file.</param>
        /// <param name="outputFileName">The fileName of the raster to create.</param>
        /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
        /// for a format that is not discernable from the file extension.  An empty string
        ///  is usually perfectly acceptable here.</param>
        /// <param name="options">For GDAL rasters, they can be created with optional parameters
        ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Generates a raster from the vectors.</returns>
        public static IRaster ToRaster(IFeatureSet fs, Extent extent, double cellSize, string fieldName,
                                       string outputFileName,
                                       string driverCode, string[] options, IProgressHandler progressHandler)
        {
            Extent env = extent;

            if (cellSize == 0)
            {
                if (env.Width < env.Height)
                {
                    cellSize = env.Width / 256;
                }
                else
                {
                    cellSize = env.Height / 256;
                }
            }
            int w = (int)Math.Ceiling(env.Width / cellSize);

            if (w > 8000)
            {
                w        = 8000;
                cellSize = env.Width / 8000;
            }
            int h = (int)Math.Ceiling(env.Height / cellSize);

            if (h > 8000)
            {
                h = 8000;
            }
            Bitmap   bmp = new Bitmap(w, h);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Transparent);
            g.SmoothingMode     = SmoothingMode.None;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            Hashtable colorTable;
            MapArgs   args = new MapArgs(new Rectangle(0, 0, w, h), env, g);

            switch (fs.FeatureType)
            {
            case FeatureType.Polygon:
            {
                MapPolygonLayer mpl = new MapPolygonLayer(fs);
                PolygonScheme   ps  = new PolygonScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            case FeatureType.Line:
            {
                MapLineLayer mpl = new MapLineLayer(fs);
                LineScheme   ps  = new LineScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            default:
            {
                MapPointLayer mpl = new MapPointLayer(fs);
                PointScheme   ps  = new PointScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;
            }
            Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType;

            // We will try to convert to double if it is a string
            if (tp == typeof(string))
            {
                tp = typeof(double);
            }
            InRamImageData image = new InRamImageData(bmp, env);
            ProgressMeter  pm    = new ProgressMeter(progressHandler, "Converting To Raster Cells", h);

            IRaster output;

            output        = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options);
            output.Bounds = new RasterBounds(h, w, env);

            double dtMax       = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", ""));
            double dtMin       = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", ""));
            double noDataValue = output.NoDataValue;

            if (dtMin <= noDataValue && dtMax >= noDataValue)
            {
                if (dtMax != GetFieldValue(tp, "MaxValue"))
                {
                    output.NoDataValue = noDataValue;
                }
                else if (dtMin != GetFieldValue(tp, "MinValue"))
                {
                    output.NoDataValue = noDataValue;
                }
            }

            List <RcIndex> locations   = new List <RcIndex>();
            List <string>  failureList = new List <string>();

            for (int row = 0; row < h; row++)
            {
                for (int col = 0; col < w; col++)
                {
                    Color c = image.GetColor(row, col);
                    if (c.A == 0)
                    {
                        output.Value[row, col] = output.NoDataValue;
                    }
                    else
                    {
                        if (colorTable.ContainsKey(c) == false)
                        {
                            if (c.A < 125)
                            {
                                output.Value[row, col] = output.NoDataValue;
                                continue;
                            }

                            // Use a color matching distance to pick the closest member
                            object val = GetCellValue(w, h, row, col, image, c, colorTable, locations);

                            output.Value[row, col] = GetDouble(val, failureList);
                        }
                        else
                        {
                            output.Value[row, col] = GetDouble(colorTable[c], failureList);
                        }
                    }
                }
                pm.CurrentValue = row;
            }
            const int maxIterations = 5;
            int       iteration     = 0;

            while (locations.Count > 0)
            {
                List <RcIndex> newLocations = new List <RcIndex>();
                foreach (RcIndex location in locations)
                {
                    object val = GetCellValue(w, h, location.Row, location.Column, image,
                                              image.GetColor(location.Row, location.Column), colorTable, newLocations);
                    output.Value[location.Row, location.Column] = GetDouble(val, failureList);
                }
                locations = newLocations;
                iteration++;
                if (iteration > maxIterations)
                {
                    break;
                }
            }

            pm.Reset();
            return(output);
        }
Exemplo n.º 5
0
        /// <summary>
        /// This draws content from the specified geographic regions onto the specified graphics
        /// object specified by MapArgs.
        /// </summary>
        public void DrawRegions(MapArgs args, List <DsExtent> regions)
        {
            // If this layer is not marked visible, exit
            if (!IsVisible)
            {
                return;
            }

            _stopwatch.Reset();

            var region = regions.FirstOrDefault() ?? args.GeographicExtents;

            if (!Monitor.TryEnter(_drawLock))
            {
                return;
            }

            LogManager.DefaultLogManager.LogMessage("MAP   : " + region, DialogResult.OK);

            // If we have a target projection, so project extent to providers extent
            var geoExtent = _targetProjection == null
                                    ? region
                                    : region.Intersection(Extent).Reproject(_targetProjection, _sourceProjection);

            LogManager.DefaultLogManager.LogMessage("SOURCE: " + geoExtent, DialogResult.OK);

            if (geoExtent.IsEmpty())
            {
                LogManager.DefaultLogManager.LogMessage("Skipping because extent is empty!", DialogResult.OK);
                Monitor.Exit(_drawLock);
                return;
            }

            BtExtent extent;

            try
            {
                extent = ToBrutileExtent(geoExtent);
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogManager.Exception(ex);
                Monitor.Exit(_drawLock);
                return;
            }

            if (double.IsNaN(extent.Area))
            {
                LogManager.DefaultLogManager.LogMessage("Skipping because extent is empty!", DialogResult.OK);
                Monitor.Exit(_drawLock);
                return;
            }

            var pixelSize = extent.Width / args.ImageRectangle.Width;

            var tileSource = _configuration.TileSource;
            var schema     = tileSource.Schema;
            var level      = _level = Utilities.GetNearestLevel(schema.Resolutions, pixelSize);

            _tileFetcher.Clear();
            var tiles       = new List <TileInfo>(Sort(schema.GetTileInfos(extent, level), geoExtent.Center));
            var waitHandles = new List <WaitHandle>();
            var tilesNotImmediatelyDrawn = new List <TileInfo>();

            LogManager.DefaultLogManager.LogMessage(string.Format("Trying to get #{0} tiles: ", tiles.Count),
                                                    DialogResult.OK);

            // Set up Tile reprojector
            var tr = new TileReprojector(args, _sourceProjection, _targetProjection);


            var sw = new Stopwatch();

            sw.Start();

            // Store the current transformation
            var transform  = args.Device.Transform;
            var resolution = schema.Resolutions[level];

            foreach (var info in tiles)
            {
                var are       = _tileFetcher.AsyncMode ? null : new AutoResetEvent(false);
                var imageData = _tileFetcher.GetTile(info, are);
                if (imageData != null)
                {
                    //DrawTile
                    DrawTile(args, info, resolution, imageData, tr);
                    continue;
                }
                if (are == null)
                {
                    continue;
                }

                waitHandles.Add(are);
                tilesNotImmediatelyDrawn.Add(info);
            }

            //Wait for tiles
            foreach (var handle in waitHandles)
            {
                handle.WaitOne();
            }

            //Draw the tiles that were not present at the moment requested
            foreach (var tileInfo in tilesNotImmediatelyDrawn)
            {
                DrawTile(args, tileInfo, resolution, _tileFetcher.GetTile(tileInfo, null), tr);
            }

            //Restore the transform
            args.Device.Transform = transform;

            sw.Stop();

            Debug.WriteLine("{0} ms", sw.ElapsedMilliseconds);
            Debug.Write(string.Format("Trying to render #{0} tiles: ", tiles.Count));

            LogManager.DefaultLogManager.LogMessage(string.Format("{0} ms", sw.ElapsedMilliseconds), DialogResult.OK);
            //if (InvalidRegion != null)
            //    MapFrame.Invalidate();

            //_stopwatch.Restart();
            Monitor.Exit(_drawLock);
        }
Exemplo n.º 6
0
        public void TestLayerGetImage()
        {
            List <string> fileNames = new List <string>()
            {
                @"E:\LC\数据\line1.shp",
                //@"E:\LC\数据\polygon.shp" ,
                //@"E:\LC\数据\双流\2014年裁剪影像.img"
            };

            foreach (var fileName in fileNames)
            {
                using (var layer = LayerManager.Default.OpenLayer(fileName))
                {
                    if (layer is IFeatureLayer featureLayer)
                    {
                        var lineSymbolizer = featureLayer.DefaultCategory.Symbolizer as ILineSymbolizer;
                        if (lineSymbolizer != null)
                        {
                            var marker = new PointSymbolizer();
                            marker.Symbols[0] = new PointSimpleSymbol(Color.Red, PointShape.Triangle, 10)
                            {
                                UseOutLine = false
                            };
                            ILineSymbol symbol = new LineMarkerSymbol
                            {
                                Color  = Color.Black,
                                Width  = 3,
                                Marker = marker
                            };
                            lineSymbolizer.Symbols[0] = symbol;
                            lineSymbolizer.Symbols.Insert(0, new LineSimpleSymbol());
                        }
                    }

                    Rectangle rectangle = new Rectangle(0, 0, 256, 256);
                    using (var image = new Bitmap(rectangle.Width, rectangle.Height))
                    {
                        //var marker = new PointSymbolizer();
                        //marker.Symbols[0] = new PointSimpleSymbol(Color.Red, PointShape.Triangle, 10)
                        //{
                        //    UseOutLine = false
                        //};
                        //SizeF size = marker.Size;
                        //int imgWidth = (int)Math.Ceiling(size.Width);
                        //int imgHeight = (int)Math.Ceiling(size.Height);
                        ////Image markerImage = Image.Load(@"C:\Users\lc156\Desktop\arrow.png");
                        //Image markerImage = new Bitmap(imgWidth, imgHeight);
                        //marker.Symbols[0].Angle = -45;
                        //using (Graphics g = Graphics.FromImage(markerImage))
                        //{
                        //    marker.DrawLegend(g, new Rectangle(0, 0, imgWidth, imgHeight));
                        //}
                        //var brush = new TextureBrush(markerImage);
                        //float[] dashPattern = null;
                        //var pen = new Pen(brush, size.Height)
                        //{
                        //    DashPattern= dashPattern
                        //};
                        //using (Graphics g = Graphics.FromImage(image))
                        //{
                        //    var points = new PointF[] { new PointF(0, 255), new PointF(255, 0) };
                        //    //var points = new PointF[] { new PointF(0, 0), new PointF(255, 255) };
                        //    //var points = new PointF[] { new PointF(0, 128), new PointF(255, 128) };
                        //    g.DrawLines(pen, points);
                        //    g.DrawLines(new Pen(Color.Blue, 1), points);
                        //    //marker.DrawPoint(x, 1, new PointF(128, 128));
                        //    //lineSymbolizer.DrawLine(x, 1, new PointF[] { new PointF(0, 128), new PointF(128, 128) }.ToPath());
                        //}
                        var extent = layer.Extent.Copy();
                        ViewHelper.GetViewEnvelope(extent, rectangle);
                        using (Graphics g = Graphics.FromImage(image))
                        {
                            MapArgs mapArgs = new MapArgs(rectangle, extent, g);
                            layer.Draw(g, rectangle, extent);
                        }
                        image.Save(@"C:\Users\lc156\Desktop\tmp\123.png");
                    }
                }
            }
        }