Отображение карты в изображение SVG, PNG, JPG с использованием GIS C# Library
Обзор отображения карты
С помощью Aspose.GIS для .NET C# API вы можете отобразить карту из Shapefile, FileGDB, GeoJSON, KML или других поддерживаемых форматов файлов в SVG, PNG, JPEG или BMP.
Вот код на C#, иллюстрирующий, как отобразить карту из shapefile в SVG с использованием настроек по умолчанию:
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET | |
using (var map = new Map(800, 400)) | |
{ | |
map.Add(VectorLayer.Open(dataDir + "land.shp", Drivers.Shapefile)); | |
map.Render(dataDir + "land_out.svg", Renderers.Svg); | |
} |
Вот результат:
Давайте посмотрим на код подробнее.
Во-первых, мы создаем экземпляр объекта Map . Он представляет собой коллекцию слоев из различных источников, которые можно отобразить. Карта имеет размер, при котором она должна быть отображена. Здесь мы устанавливаем ширину карты 800 пикселей и высоту 400 пикселей.
Обратите внимание, что Map заключен в оператор using. Это необходимо, потому что карта отслеживает все ресурсы, добавленные к ней, и удаляет их, когда мы заканчиваем рендеринг и объект Map утилизирован.
Затем мы добавляем слой из файла на карту. Каждый слой отображается поверх предыдущего слоя в порядке их добавления на карту. Более подробную информацию о том, как открывать векторные слои, можно найти здесь.
Наконец, мы вызываем Map.Render, чтобы отобразить карту в файл. Мы указываем путь к месту сохранения результирующего файла и отрисовщик для использования. Класс Renderers содержит ссылки на все отрисовщики, включенные в Aspose.GIS. Например, вы можете указать Renderers.Png вместо Renderers.Svg в приведенном выше примере, чтобы отобразить карту в PNG-файл.
Расширенное стилизование
С помощью API Aspose.GIS вы можете настроить рендеринг и стили функций для достижения желаемого внешнего вида.
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET | |
using (var map = new Map(800, 476)) | |
{ | |
var baseMapSymbolizer = new SimpleFill { FillColor = Color.Salmon, StrokeWidth = 0.75 }; | |
map.Add(VectorLayer.Open(dataDir + "basemap.shp", Drivers.Shapefile), baseMapSymbolizer); | |
var citiesSymbolizer = new SimpleMarker() { FillColor = Color.LightBlue }; | |
citiesSymbolizer.FeatureBasedConfiguration = (feature, symbolizer) => | |
{ | |
var population = feature.GetValue<int>("population"); | |
symbolizer.Size = 10 * population / 1000; | |
if (population < 2500) | |
{ | |
symbolizer.FillColor = Color.GreenYellow; | |
} | |
}; | |
map.Add(VectorLayer.Open(dataDir + "points.geojson", Drivers.GeoJson), citiesSymbolizer); | |
map.Render(dataDir + "cities_out.svg", Renderers.Svg); | |
} |
Рисование растра в карте
С помощью Aspose.GIS для .NET вы можете отображать карту из растровых форматов.
Отображение с настройками по умолчанию
Вот как отобразить карту из GeoTIFF в SVG, используя настройки по умолчанию:
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET | |
string filesPath = RunExamples.GetDataDir(); | |
using (var map = new Map(500, 500)) | |
{ | |
var layer = Drivers.GeoTiff.OpenLayer(Path.Combine(filesPath, "raster_float32.tif")); | |
// Conversion to colors is detected automatically. | |
// The maximum and minimum values are calculated and linear interpolation is used. | |
map.Add(layer); | |
map.Render(filesPath + "raster_float32_out.svg", Renderers.Svg); | |
} |
Отображение искаженных растров
С помощью Aspose.GIS вы можете отображать растр с искаженными ячейками растра.
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET | |
string filesPath = RunExamples.GetDataDir(); | |
using (var map = new Map(500, 500)) | |
{ | |
// use background color | |
map.BackgroundColor = Color.Azure; | |
var layer = Drivers.GeoTiff.OpenLayer(Path.Combine(filesPath, "raster_skew.tif")); | |
// Conversion to colors is detected automatically. | |
// The maximum and minimum values are calculated and linear interpolation is used. | |
map.Add(layer); | |
map.Render(filesPath + "raster_skew_out.svg", Renderers.Svg); | |
} |
Отображение в полярной пространственной ссылке
Aspose.GIS позволяет использовать полярные пространственные ссылки в процессе отображения карты.
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET | |
string filesPath = RunExamples.GetDataDir(); | |
// make own multi colorizer it works faster than auto-detection | |
var colorizer = new MultiBandColor() | |
{ | |
RedBand = new BandColor() { BandIndex = 0, Min = 0, Max = 255 }, | |
GreenBand = new BandColor() { BandIndex = 1, Min = 0, Max = 255 }, | |
BlueBand = new BandColor() { BandIndex = 2, Min = 0, Max = 255 } | |
}; | |
using (var map = new Map(500, 500)) | |
{ | |
// setup the polar extent and coordinate system (gnomonic spatial reference) | |
map.SpatialReferenceSystem = SpatialReferenceSystem.CreateFromEpsg(102034); | |
map.Extent = new Extent(-180, 60, 180, 90) { SpatialReferenceSystem = SpatialReferenceSystem.Wgs84 }; | |
map.BackgroundColor = Color.Azure; | |
// open geo-tiff | |
var layer = Drivers.GeoTiff.OpenLayer(Path.Combine(filesPath, "raster_countries.tif")); | |
// draw | |
map.Add(layer, colorizer); | |
map.Render(filesPath + "raster_countries_gnomonic_out.png", Renderers.Png); | |
} |