如何在 C# 中从必应地图创建缩略图/快照以实现通用解决方案



我有一个通用的解决方案,其平台支持Windows Phone。用户点击必应地图后,将创建一个图钉,还会创建地图的快照,但此图像不包含图钉。

我正在使用Windows.UI.Xaml.Controls.Maps.MapControl与这个xaml:-

XAML:

<mp:MapControl x:Name="mpWinPh"
Grid.Row="1"
Width="{Binding ElementName=ControlRoot,
Path=Width}"
Height="{StaticResource ActivityLogGfxSize}"
MapServiceToken="{Binding Credentials}"
MapTapped="mpWinPh_MapTapped" />

C#:

private async void mpWinPh_MapTapped(MapControl sender, MapInputEventArgs args)
{
var location = args.Location;
BasicGeoposition snPosition = new BasicGeoposition
{
Latitude = location.Position.Latitude,
Longitude = location.Position.Longitude,
Altitude = location.Position.Altitude
};
Geopoint snPoint = new Geopoint(snPosition);
MapIcon icon = new MapIcon { Location = snPoint };
mpWinPh.Center = snPoint;
mpWinPh.ZoomLevel = 15;
mpWinPh.MapElements.Clear();
mpWinPh.MapElements.Add(icon);
Field.GpsCoordinate coordinate = new Field.GpsCoordinate { Latitude = location.Position.Latitude, Longitude = location.Position.Longitude };
(viewModel as LocationControlViewModel).UpdateGps(coordinate);
await SaveImage();
}
private async Task SaveImage()
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(mpWinPh);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
// Useful for rendering in the correct DPI
var displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
byte[] resizedData = new byte[stream.Size];
await stream.ReadAsync(resizedData.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
await SaveStreamToTempLocation(() => Task.FromResult(new MemoryStream(resizedData) as Stream));
}

由于向地图添加数据是一项异步操作,因此在向地图添加任何数据(例如 MapIcon(或使用任何视图设置 API 更改地图视图后,应等到地图控件的 LoadStatus 变为 MapLoadStatus.Loaded。 这表示地图控件已完成异步工作并已完全呈现。可以在映射控件上注册 LoadStatusChanged 事件。

最新更新