在Xamarin.Forms中截取屏幕截图

时间:2017-04-13 22:35:13

标签: xamarin xamarin.forms screenshot

我已经查看并广泛测试this post。下面是PCL上截屏按钮的代码。

async void OnScreenshotButtonClicked(object sender, EventArgs args) {
    var imageSender = (Image)sender;
    var ScreenShot = DependencyService.Get<IScreenshotManager>().CaptureAsync();
    await DisplayAlert("Image Saved", "The image has been saved to your device's picture album.", "OK");
}

所以我的问题是如何将byte[]变成图像并将其保存到设备中......
对于我的生活,我无法找到将图像保存到设备的方法。任何帮助将不胜感激!!!谢谢!

1 个答案:

答案 0 :(得分:0)

与Jason在评论中提到的一样,您可以通过添加File.WriteAllBytes();行来扩展平台项目中的代码并从那里保存文件。

或者您可以将其解耦并创建另一个DependencyService。例如,创建IScreenshotService之类的:DependencyService.Get<IScreenshotService>().SaveScreenshot("MyScreenshot123", ScreenShot);

并创建这样的实现:

PCL

public interface IScreenshotService
{
    SaveScreenshot(string filename, byte[] imageBytes);`
}

的iOS

[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService_iOS))]
 
namespace YourApp.iOS
{
    public class ScreenshotService_iOS: IScreenshotService
    {
        public void SaveScreenshot(string filename, byte[] imageBytes)
        {
            var screenshot = new UIImage(NSData.FromArray(imageBytes));

            screenshot.SaveToPhotosAlbum((image, error) =>
            {
                // Catch any error here
                if(error != null)
                    Console.WriteLine(error.ToString());

                // If you want you can access the image here from the image parameter
            });
        }
    }
}

的Android

[assembly: Xamarin.Forms.Dependency(typeof(Picture_Droid))]
 
namespace YourApp.Droid
{
    public class ScreenshotService_Android : IScreenshotService
    {
        public void SaveScreenshot(string filename, byte[] imageBytes)
        {
            var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
            
            var pictures = dir.AbsolutePath;
            
            // You might want to add a unique id like GUID or timestamp to the filename, else you could be overwriting an older image

            string filePath = System.IO.Path.Combine(pictures, filename);

            try
            {
                // Write the image
                File.WriteAllBytes(filePath, imageData);

                // With this we add the image to the image library on the device
                var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);

                mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
                Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

不要忘记在Android应用上添加相应的权限(可能WRITE_EXTERNAL_STORAGE就足够了)

最后,您可以查看第三方库,例如Splat