我正在尝试实现一些逻辑来分享我的 webView 的图像和一些额外的信息。如果我在没有捕获屏幕的情况下这样做,它会完美运行:
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
if (await GetShareContent(e.Request))
{
if (String.IsNullOrEmpty(e.Request.Data.Properties.Title))
{
e.Request.FailWithDisplayText("Nenhum título adicionado");
}
}
}
private async Task<bool> GetShareContent(DataRequest request, StorageFile file)
{
bool succeeded = false;
string text = "Dados do Arquivo:" + Environment.NewLine + webViewModel.Name;
string dataPackageText = text;
if (!String.IsNullOrEmpty(dataPackageText))
{
DataPackage requestData = request.Data;
requestData.Properties.Title = "Target";
requestData.Properties.Description = webViewModel.Name;
requestData.SetText(dataPackageText);
succeeded = true;
}
else
{
request.FailWithDisplayText("Não há nada para compartilhar");
}
return succeeded;
}
但是,如果我尝试相同的方法只是添加捕获的图像,它不起作用,没有显示任何异常,只是消息:“Não há nada para compartilhar agora”(现在没有什么可分享的)
我不知道发生了什么事。不起作用的代码:
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
StorageFile file = await captureScreen();
if (await GetShareContent(e.Request, file))
{
if (String.IsNullOrEmpty(e.Request.Data.Properties.Title))
{
e.Request.FailWithDisplayText("Nenhum título adicionado");
}
}
}
private async Task<StorageFile> captureScreen()
{
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(webView, (int)webView.Width, (int)webView.Height);
Image myImage = new Image();
myImage.Source = renderTargetBitmap;
var file = await App.rootDir.CreateFileAsync("screenCapture.jpg", CreationCollisionOption.ReplaceExisting);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)webView.Width, (uint)webView.Height,
96, 96, bytes);
await encoder.FlushAsync();
}
return file;
}
我虽然可能会发生这种情况,因为在调用共享时未读取图像,但我正在使用等待。我的 jpeg 是完美创建的。