【问题标题】:How to convert a LinearLayout to image?如何将 LinearLayout 转换为图像?
【发布时间】:2012-04-29 18:01:17
【问题描述】:

我尝试使用以下代码将LinearLayout 转换为图像:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LinearLayout lyt = (LinearLayout) findViewById(R.id.lyt);
    lyt.setDrawingCacheEnabled(true);
    lyt.buildDrawingCache(true);

    Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());

    ImageView img = (ImageView) findViewById(R.id.imageView1);
    img.setImageBitmap(b);

}

但我收到了NullPointerException

Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());

布局 XML 的位置:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <LinearLayout
        android:id="@+id/lyt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3" />

    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

【问题讨论】:

    标签: android bitmap android-linearlayout


    【解决方案1】:

    试试下面的代码,它可以工作

    在清单中添加以下权限

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

    MainActivity.java

        public class MainActivity extends Activity implements OnClickListener{
        private LinearLayout linearLayout;
        private Button saveBtn;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            linearLayout = (LinearLayout) findViewById(R.id.linearLayout_view);
            saveBtn = (Button) findViewById(R.id.save_btn);
            saveBtn.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
            case R.id.save_btn:
                File file = saveBitMap(this, linearLayout);    //which view you want to pass that view as parameter
                if (file != null) {
                    Log.i("TAG", "Drawing saved to the gallery!");
                } else {
                    Log.i("TAG", "Oops! Image could not be saved.");
                }
                break;
            default:
                break;
            }
    
        private File saveBitMap(Context context, View drawView){
            File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
            if (!pictureFileDir.exists()) {
                boolean isDirectoryCreated = pictureFileDir.mkdirs();
                if(!isDirectoryCreated)
                    Log.i("ATG", "Can't create directory to save the image");
                return null;
            }
            String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
            File pictureFile = new File(filename);
            Bitmap bitmap =getBitmapFromView(drawView);
            try {
                pictureFile.createNewFile();
                FileOutputStream oStream = new FileOutputStream(pictureFile);
                bitmap.compress(CompressFormat.PNG, 100, oStream);
                oStream.flush();
                oStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("TAG", "There was an issue saving the image.");
            }       
                scanGallery( context,pictureFile.getAbsolutePath());
            return pictureFile;
        }
        //create bitmap from view and returns it
        private 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;
        }
        // used for scanning gallery
        private void scanGallery(Context cntx, String path) {
            try {
                MediaScannerConnection.scanFile(cntx, new String[] { path },null, new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 谢谢 :) 您的回答向我展示了设置背景的重要提示,这就像魅力一样。
    【解决方案2】:

    我的猜测是您正在 onCreate 中执行该代码。问题在于视图尚未布局。调用 lyt.measure 或稍后调用代码。例如:调用 super.onLayout() 后到 onSizeChanged() 或 onLayout()。

    【讨论】:

    • 如何调用 lyt.onMeasure() ??!
    • 抱歉函数是 measure()。但我建议稍后创建位图而不是调用 measure()。
    【解决方案3】:
    Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());
    

    该行中唯一可以是null 的是lyt,其余的不能。您可能尚未设置布局,在这种情况下,findViewById() 将返回 null

    您必须先执行setContentView(),然后才能执行findViewById()

    【讨论】:

    • 嗯,这应该意味着错误不会发生在该行上,而是在 Bitmap.createBitmap()lyt.getDrawingCache() 内的某个地方。我猜 Renard 是对的,如果视图没有自己布局,他们就不知道如何绘制自己。
    【解决方案4】:

    以下是将xml布局转换为位图图像的代码片段

    private Bitmap convertLayoutToImage() {
            LinearLayout linearView = (LinearLayout) this.getLayoutInflater(null).inflate(R.layout
                    .marker_layout, null, false); //you can pass your xml layout
    
            linearView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            linearView.layout(0, 0, linearView.getMeasuredWidth(), linearView.getMeasuredHeight());
    
            linearView.setDrawingCacheEnabled(true);
            linearView.buildDrawingCache();
            return linearView.getDrawingCache();// creates bitmap and returns the same
        }
    

    【讨论】:

      【解决方案5】:

      看看对你有没有帮助:

      Converting Views to Bitmap Images in Android

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 2019-07-04
        • 2011-08-15
        • 2012-03-11
        • 1970-01-01
        相关资源
        最近更新 更多