Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Xamarin.Forms — Capture Screenshots Using DependencyService

DZone's Guide to

Xamarin.Forms — Capture Screenshots Using DependencyService

Learn how to use DependencyService in Xamarin.Forms apps to call platform-specific functionality from shared code and capture screenshots.

· Mobile Zone ·
Free Resource

Introduction

Image title

Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also a simpler solution to distribute the data files with an app.

DependencyService

Image title

DependencyService allows apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do.

DependencyService is a dependency resolver. In practice, an interface is defined and DependencyService finds the correct implementation of that interface from the various platform projects.

Xamarin.Forms apps need three components to use DependencyService:

  1. Interface – The required functionality is defined by an interface in shared code.

  2. Implementation Per Platform – Classes that implement the interface must be added to each platform project.

  3. Registration – Each implementing class must be registered with DependencyService via a metadata attribute. Registration enables DependencyService to find the implementing class and supply it in place of the interface at runtime.

  4. Call to DependencyService – Shared code needs to explicitly call DependencyService to ask for implementations of the interface.

Prerequisites

  • Visual Studio 2017 (Windows or Mac)

Setting Up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Choose the Cross-platform App project under Visual C#-->Cross-platform in the New Project dialog.

Image title

Now Select the Blank App and Choose Portable Class Library(PCL).

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Setting Up the User Interface

Go to MainPage.Xaml and write the following code.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinFormsScreenShot"
             x:Class="XamarinFormsScreenShot.MainPage">
    <ContentPage.Content>
        <StackLayout>
            <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">
                <Image  x:Name="imgBanner"  WidthRequest="300"></Image>
                <Button Text="Capture Me" WidthRequest="100" x:Name="btnCapture" Clicked="btnCapture_Clicked"></Button>
                <Frame BackgroundColor="Gray" Margin="10" Padding="5" >
                <Image x:Name="imgCaptured"></Image>
                </Frame>
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Click the Play button to try it out.

Image title

Creating the Interface

Create an interface in Xamarin.Forms PCL.

Go to Solution—>PCL—>Right click—>New—>Interface—>IScreen.cs.

Now, write the following code:

IScreen.cs

using System.Threading.Tasks;

namespace XamarinFormsScreenShot
{
    public interface IScreen
    {
        Task<byte[]> CaptureScreenAsync();
    }
}


Implementation per Platform

Android Implementation

Go to Solution—>Android —>Right click—>New—>Class—> ScreenHelper.cs

Now, write the following code for Capture Current Screen.

ScreenHelper.cs

using XamarinFormsScreenShot.Droid;
using Android.Graphics;
using System.IO;

[assembly: Xamarin.Forms.Dependency(typeof(ScreenHelper))]
namespace XamarinFormsScreenShot.Droid
{
    public class ScreenHelper : IScreen
    {
        public async Task<byte[]> CaptureScreenAsync()
        {
            var activity = Xamarin.Forms.Forms.Context as MainActivity;
            if (activity == null)
            {
                return null;
            }
            var view = activity.Window.DecorView;
            view.DrawingCacheEnabled = true;
            Bitmap bitmap = view.GetDrawingCache(true);
            byte[] bitmapData;

            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
                bitmapData = stream.ToArray();
            }

            return bitmapData;
        }
    }
}

Call to DependencyService

In this step, call the DependencyService for your PCL.

MainPage.Xaml.cs

using Xamarin.Forms;

namespace XamarinFormsScreenShot
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            imgBanner.Source = ImageSource.FromResource("XamarinFormsScreenShot.images.banner.png");
            imgCaptured.Source = ImageSource.FromResource("XamarinFormsScreenShot.images.default.jpg");

        }

        private async void btnCapture_Clicked(object sender, EventArgs e)
        {
            //Call Dependency Service
            var imageByte = await DependencyService.Get<IScreen>().CaptureScreenAsync();
            imgCaptured.Source = ImageSource.FromStream(() => new MemoryStream(imageByte));
        }
    }
}

Click the Play button to try it out.

Image title

I hope you understand how to Capture ScreenShot Using DependencyService.

Thanks for reading. Please share comments and feedback.

Topics:
xamarin ,tutorial ,mobile ,mobile app development ,cross platform development ,xamarin.forms

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}