如何在windows phone 8.1 SDK中编程抓取屏幕
本文关键字:SDK 编程 抓取 屏幕 windows phone | 更新日期: 2023-09-27 18:05:39
任何想法如何捕获屏幕在SDK 8.1 windows phone从代码?对于windows phone 7.5,我已经看到了代码并试图使用,但失败了。(
你可以使用RenderTargetBitmap
并传递给它一个代表页面的FrameworkElement,然后从中渲染一个位图。
private async Task<RenderTargetBitmap> CreateBitmapFromElement(FrameworkElement uielement)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
return renderTargetBitmap;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
return null;
}
试试这样写:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
this.imagePreview.Source = await CreateBitmapFromElement(this);
}
页面上的XAML:
<Grid x:Name="controlsGrid">
<Button Click="ButtonBase_OnClick">take screenshot</Button>
<Image x:Name="imagePreview"
Height="200" VerticalAlignment="Bottom"
Stretch="UniformToFill" />
</Grid>
要将渲染的图像保存为图像文件,我们必须将其发送到流,将其编码为我们想要的文件类型。
这是一个我们可以使用的方法(它接受一个UI元素,一个流和一个Guid):
//Creates RenderTargetBitmap from UI Element
async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
var pixels = await renderTargetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
logicalDpi,
logicalDpi,
pixels.ToArray());
await encoder.FlushAsync();
return renderTargetBitmap;
}
我们可以使用Windows Phone 8.1上的FileSavePicker类来决定文件类型,名称和保存位置。
void CreateFileSavePicker()
{
//Create the picker object
FileSavePicker savePicker = new FileSavePicker();
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add
(
"Image", new List<string>() { ".jpg" });
// Default file name if the user does not type one in or select // a file to replace
savePicker.SuggestedFileName = "Screenshot";
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
//// Open the picker for the user to pick a file
savePicker.ContinuationData["Operation"] = "SomeDataOrOther";
savePicker.PickSaveFileAndContinue();
}
当用户选择文件位置时,它会返回到ContinueFileSavePicker。
public async void ContinueFileSavePicker(Windows.ApplicationModel.Activation.FileSavePickerContinu ationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
Guid encoderId = BitmapEncoder.JpegEncoderId;
try
{
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await CaptureToStreamAsync(LayoutRoot, stream, encoderId);
}
}
catch (Exception ex)
{
DisplayMessage(ex.Message);
}
}
}