Looking for Xamarin Forms Developers?
We have a dedicated team of experienced certified professionals who have the objective of serving customers with better expectations and experience.
Read MoreXamarin Forms is a cross-platform development framework, but it doesn’t have inbuilt functionality to take a screenshot. To do stuff which needs to depend heavily on Native Platform, it leverages this by multiple ways, here we will look at taking a screenshot by Dependency Injection.
To access native platform features via Dependency Injection, we need to create 1 file in .net standard project and 1 file each for Platform Specific Project. Here we are talking about Android and iOS, so we will create 1 file in Android and 1 file in iOS project.
Make IScreenshotService.cs
public interface IScreenshotService
{
Task<byte[]> CaptureAsync();
}
Make ScreenshotService.cs
[assembly: Dependency(typeof(ScreenshotService))]
namespace Screenshot.Droid.Dependencies
{
public class ScreenshotService : IScreenshotService
{
public async Task<byte[]> CaptureAsync()
{
var view = Xamarin.Essentials.Platform.CurrentActivity.Window.DecorView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream())
{
await bitmap.CompressAsync(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
view.DrawingCacheEnabled = false;
return bitmapData;
}
}
}
Make ScreenshotService.cs
[assembly: Dependency(typeof(ScreenshotService))]
namespace Screenshot.iOS.Dependencies
{
public class ScreenshotService : IScreenshotService
{
public async Task<byte[]> CaptureAsync()
{
var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
UIGraphics.BeginImageContext(view.Frame.Size);
view.DrawViewHierarchy(view.Frame, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
using (var imageData = image.AsPNG())
{
var bytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
return bytes;
}
}
}
}
To Take the screenshot anywhere in your app, just write the below code:
var screenshotData = await DependencyService.Get<IScreenshotService>().CaptureAsync();
You can either save this to file storage or upload to api to send it to the support team.
If you want to display the screenshot, you can use it with the help of Stream, shown as below
var stream = new MemoryStream(screenshotData);
ImageData.Source = ImageSource.FromStream(() => stream);
Enjoy Coding 🙂
I hereby agree to receive newsletters from Mobmaxime and acknowledge company's Privacy Policy.