2012-01-05 6 views
8

Utilizo el siguiente código para convertir, pero parece que solo puede obtener el contenido en la pantalla y no puede obtener el contenido en la pantalla.¿Cómo convertir todo el contenido en una vista de desplazamiento en un mapa de bits?

¿Hay alguna manera de obtener todo el contenido incluso sin desplazamiento?

Bitmap viewBitmap = Bitmap.createBitmap(mScrollView.getWidth(),mScrollView.getHeight(),Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(viewBitmap); 
mScrollView.draw(canvas); 

Respuesta

15

Podemos convertir todo el contenido de un ScrollView una imagen de mapa de bits a usar el código que se muestra a continuación

private void takeScreenShot() 
{ 
    View u = ((Activity) mContext).findViewById(R.id.scroll); 

    HorizontalScrollView z = (HorizontalScrollView) ((Activity) mContext).findViewById(R.id.scroll); 
    int totalHeight = z.getChildAt(0).getHeight(); 
    int totalWidth = z.getChildAt(0).getWidth(); 

    Bitmap b = getBitmapFromView(u,totalHeight,totalWidth);    

    //Save bitmap 
    String extr = Environment.getExternalStorageDirectory()+"/Folder/"; 
    String fileName = "report.jpg"; 
    File myPath = new File(extr, fileName); 
    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(myPath); 
     b.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
     fos.flush(); 
     fos.close(); 
     MediaStore.Images.Media.insertImage(mContext.getContentResolver(), b, "Screen", "screen"); 
    }catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) { 

    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(returnedBitmap); 
    Drawable bgDrawable = view.getBackground(); 
    if (bgDrawable != null) 
     bgDrawable.draw(canvas); 
    else 
     canvas.drawColor(Color.WHITE); 
    view.draw(canvas); 
    return returnedBitmap; 
} 
+0

este es el que no trabaja cuando las opiniones de uso scrollTo que deseen desplazarse internamente su contenido http://developer.android.com/reference/android/view/View.html#scrollTo% 28int,% 20int% 29 –

+0

funciona bien ... ¡gracias –

0

El problema aquí es que el único contenido real de píxeles que existe es el que está visible en la pantalla. Android y otras plataformas móviles son muy cuidadosas con el uso de la memoria y una de las formas en que una vista de desplazamiento puede mantener el rendimiento es no extraer nada que esté fuera de la pantalla. Por lo tanto, no existe un mapa de bits "completo" en ninguna parte: la memoria que contiene el contenido que se mueve fuera de la pantalla se recicla.

1

Necesita obtener el ancho y alto total de la vista de desplazamiento, o creó viewBitmap es demasiado pequeño para contener el contenido completo de la vista de desplazamiento.

verificación de este enlace Android: Total height of ScrollView

5

La respuesta Pops es muy buena, pero en algunos casos se podría tener que crear un mapa de bits realmente grande que podría desencadenar una excepción OutOfMemoryException al crear el mapa de bits.

Hice, pues, un poco de optimización para ser suavemente con la memoria :)

public static Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) { 

    int height = Math.min(MAX_HEIGHT, totalHeight); 
    float percent = height/(float)totalHeight; 

    Bitmap canvasBitmap = Bitmap.createBitmap((int)(totalWidth*percent),(int)(totalHeight*percent), Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(canvasBitmap); 

    Drawable bgDrawable = view.getBackground(); 
    if (bgDrawable != null) 
     bgDrawable.draw(canvas); 
    else 
     canvas.drawColor(Color.WHITE); 

    canvas.save(); 
    canvas.scale(percent, percent); 
    view.draw(canvas); 
    canvas.restore(); 

    return canvasBitmap; 
} 
1

Esta funciona para mí

para guardar el registro de mapa de bits en tiempo de ejecución permiso primera

@OnClick(R.id.donload_arrow) 
    public void DownloadBitMap() 
    { 
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) 
    { 
     downloadData(); 
        Log.e("callPhone: ", "permission"); 
       } else { 
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); 
        Toast.makeText(this, "need permission", Toast.LENGTH_SHORT).show(); 
       } 

      } 

Para obtener mapa de bits

private void downloadData() { 

     ScrollView iv = (ScrollView) findViewById(R.id.scrollView); 
     Bitmap bitmap = Bitmap.createBitmap(
       iv.getChildAt(0).getWidth()*2, 
       iv.getChildAt(0).getHeight()*2, 
       Bitmap.Config.ARGB_8888); 
     Canvas c = new Canvas(bitmap); 
     c.scale(2.0f, 2.0f); 
     c.drawColor(getResources().getColor(R.color.colorPrimary)); 
     iv.getChildAt(0).draw(c); 
     // Do whatever you want with your bitmap 
     saveBitmap(bitmap); 

    } 

Para guardar el mapa de bits

public void saveBitmap(Bitmap bitmap) { 
     File folder = new File(Environment.getExternalStorageDirectory() + 
       File.separator + "SidduInvoices"); 
     boolean success = true; 
     if (!folder.exists()) { 
      success = folder.mkdirs(); 
     } 
     if (success) { 
      // Do something on success 
     } else { 
      // Do something else on failure 
     } 

     File imagePath = new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus.png"); 

     if(imagePath.exists()) 
     { 
      imagePath=new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus"+custamername.getText().toString()+".png"); 

     } 
     FileOutputStream fos; 
     try { 
      fos = new FileOutputStream(imagePath); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
      fos.flush(); 
      fos.close(); 
      progressBar.cancel(); 


      final File finalImagePath = imagePath; 
      new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE) 
        .setTitleText("Saved") 
        .setContentText("Do you want to share this with whatsapp") 
        .setCancelText("No,cancel !") 
        .setConfirmText("Yes,share it!") 
        .showCancelButton(true) 
        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { 
         @Override 
         public void onClick(SweetAlertDialog sweetAlertDialog) { 
          sweetAlertDialog.cancel(); 
          shareImage(finalImagePath); 
         } 
        }) 
        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { 
         @Override 
         public void onClick(SweetAlertDialog sDialog) { 
          sDialog.cancel(); 

         } 
        }) 
        .show(); 




     } catch (FileNotFoundException e) { 
      Log.e("GREC", e.getMessage(), e); 
     } catch (IOException e) { 
      Log.e("GREC", e.getMessage(), e); 
     } 



    } 
+0

funcionando perfectamente! gracias .) –

Cuestiones relacionadas