在 Android 上将视图转换为位图 [英] Convert view to bitmap on Android

查看:29
本文介绍了在 Android 上将视图转换为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将视图转换为位图以预览我的视图并将其另存为图像.我尝试使用以下代码,但它创建了一个空白图像.我不明白我哪里出错了.

I need to convert a view to a bitmap to preview my view and to save it as an image. I tried using the following code, but it creates a blank image. I cannot understand where I made a mistake.

 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;
    }

享受:)

这篇关于在 Android 上将视图转换为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆