Button for screenshot / screenshot on Xamarin

0

I'm developing an App and I need it to take a screenshot, but not by the default procedure (home + power button), but by a button inserted on the screen. The button has already been created and is in the App screen, does anyone have any idea how to make this button make a screenshot?

private void Button_Clicked(object sender, System.EventArgs e)
{
  //procedimento        
}
    
asked by anonymous 18.07.2018 / 21:15

1 answer

1

The procedure of taking a print out of the screen is to draw an image file with the content displayed on the screen.

Starting from the principle that you also want to save the image generated on the SD card for example, the solution would look like this:

Add in the manifest permission to write to the card:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Add the code below into the click function of your button:

    private void Button_Clicked(object sender, System.EventArgs e)
{   
       // String que recebe o endereço da pasta onde será salva o arquivo
       string path = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "PrintDirectory");

       // Busca a view principal de sua aplicação
       View v1 = Window.DecorView.RootView;
        v1.DrawingCacheEnabled=true;

        // Cria uma cache para escrever a imagem do tipo bitmap
        Android.Graphics.Bitmap bitmap = Android.Graphics.Bitmap.CreateBitmap(v1.GetDrawingCache(true));

        // Instancia o arquivo na pasta de destino. Neste caso o nome do arquivo será de acordo com o horário, pois garante que não terá arquivos com nomes iguais
        Java.IO.File imageFile = new Java.IO.File(path, System.Environment.TickCount + ".jpg");

        //  Cria um fluxo de bytes para escrever os bytes capturados da tela         
        System.IO.MemoryStream bytes = new System.IO.MemoryStream();
        int quality = 100;


        // Verifica se a pasta destino existe, caso não exista, cria a pasta no cartão SD
        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
        if (!dir.Exists)
            dir.CreateSubdirectory(path);


        // Cria um fluxo de escrita para o arquivo destino
        Java.IO.FileOutputStream fo;
        imageFile.CreateNewFile();
        fo = new Java.IO.FileOutputStream(imageFile);

        //Converte o bitmap para JPEG
        bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, quality, bytes);

        // Escreve o arquivo com o print na pasta e depois o fecha-o
        fo.Write(bytes.ToArray());
        fo.Close();
}

A .JPEG file will be generated in the chosen folder

    
18.07.2018 / 22:00