programing

Android에서보기를 비트 맵으로 변환

copyandpastes 2021. 1. 16. 10:59
반응형

Android에서보기를 비트 맵으로 변환


뷰를 미리보고 이미지로 저장하려면 뷰를 비트 맵으로 변환해야합니다. 다음 코드를 사용해 보았지만 빈 이미지가 생성됩니다. 내가 어디에서 실수했는지 이해할 수 없습니다.

 View viewToBeConverted;  Bitmap viewBitmap =   Bitmap.createBitmap(viewToBeConverted.getWidth(), viewToBeConverted.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap); 
 viewToBeConverted.draw(canvas); 
 savephoto(“f1”, viewBitmap); 

 ////  public void savephoto(String filename,Bitmap bit)     
   {  
            File newFile = new File(Environment.getExternalStorageDirectory() + Picture_Card/"+ filename+ ".PNG");
              try 
{
                    newFile.createNewFile();                   
 try
 { 
                         FileOutputStream pdfFile = new FileOutputStream(newFile);                                                Bitmap bm = bit;                          ByteArrayOutputStream baos = new ByteArrayOutputStream();                          bm.compress(Bitmap.CompressFormat.PNG,100, baos);                                                     byte[] bytes = baos.toByteArray();                         
 pdfFile.write(bytes);                                              
      pdfFile.close();                   
 }
 catch (FileNotFoundException e) 
{                          //       

  }            
  } catch (IOException e)
 {                    //          
    }      
  }  

내 해결책은 다음과 같습니다.

  public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null) 
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else 
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
    }

즐겨 :)


내 뷰가 ViewGroup (LayoutInflater에서 부풀려 짐)이기 때문에 가장 많이 득표 한 솔루션이 작동하지 않았습니다. view.getMeasuredWidth (Height)를 사용하여 올바른 뷰 크기를 얻으려면 view.measure를 호출하여 뷰 크기를 강제로 계산해야했습니다.

public static Bitmap getBitmapFromView(View view) {
    view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    view.draw(canvas);
    return bitmap;
}

다음은 Kotlin에서 영감을 얻은 확장 프로그램입니다. Google Android Maps Utils Icon Generator

fun View.convertToBitmap(): Bitmap {
val measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
measure(measureSpec, measureSpec)
layout(0, 0, measuredWidth, measuredHeight)
val r = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888)
r.eraseColor(Color.TRANSPARENT)
val canvas = Canvas(r)
draw(canvas)
return r }

캔버스에 그리기를 사용하는 모든 답변은 GLSurfaceView에서 작동하지 않습니다.

To capture the content of a GLSurfaceView into a bitmap you should consider to implement a custom method with gl.glReadPixels inside Renderer::onDrawFrame().

A solution snippet has been posted here.


Conversion of Layout or view to bitmap :

  private Bitmap createBitmapFromLayout(View tv) {        
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.measuredHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.translate((-tv.getScrollX()), (-tv.getScrollY()));
    tv.draw(c);
    return b;
}

Without xml:

  private Bitmap createBitmapFromView() {
    TextView tv = new TextView(this);
    tv.setText("Hello Android !!");
    tv.setTextColor(Color.WHITE);
    tv.setBackgroundColor(Color.GRAY);
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.measuredHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.translate((-tv.getScrollX()), (-tv.getScrollY()));
    tv.draw(c);
    return b;
}

ReferenceURL : https://stackoverflow.com/questions/5536066/convert-view-to-bitmap-on-android

반응형