我找不到如何将地图(Xamarin.Forms.Maps.Map)保存为图像? iOS和Android有通用的方法吗?普通项目中可能有创建实现吗?
感谢您的回答。
答案 0 :(得分:0)
我已经解决了问题,那就是工作代码
公共类ScreenshotManager:IScreenshotManager { 私人唯读Activity _activity;
public ScreenshotManager(Activity activity)
{
_activity = activity;
}
public async Task<byte[]> CaptureMapAsync(Map map)
{
if (_activity == null)
{
throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
}
var renderer = Platform.GetRenderer(map);
Platform.SetRenderer(map, renderer);
var viewRenderer = renderer.View;
var mapRenderer = (MapRenderer)viewRenderer;
var mapView = mapRenderer.Control;
var mapDownloaderTask = new TaskCompletionSource<byte[]>();
mapView.GetMapAsync(new OnMapReadyCallback(m =>
{
mapDownloaderTask.SetResult(m);
}));
return await mapDownloaderTask.Task;
}
}
internal class OnMapReadyCallback : Java.Lang.Object, IOnMapReadyCallback
{
readonly Action<byte[]> handler;
public OnMapReadyCallback(Action<byte[]> handler)
{
this.handler = handler;
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
googleMap.Snapshot(new SnapshotMapCallBack(handler));
}
}
internal class SnapshotMapCallBack : Java.Lang.Object, GoogleMap.ISnapshotReadyCallback
{
readonly Action<byte[]> handler;
public SnapshotMapCallBack(Action<byte[]> handler)
{
this.handler = handler;
}
public void OnSnapshotReady(Bitmap snapshot)
{
using (var stream = new MemoryStream())
{
snapshot.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] bitmapData = stream.ToArray();
handler?.Invoke(bitmapData);
}
}
}