二維碼保存遇到問題小結

在做二維碼保存成圖片的時候遇到了幾個問題。在這裏記錄一下。也方便一下後來的同學。不足之處請指正~

1.如何將二維碼圖片(包括佈局整個頁面保存下來)保存下來?

經過查找資料發現用到的知識點是:將View轉化爲Bitmap並保存下來有一個方法是使用:View裏面有幾個方法,
setDrawingCacheEnabled(boolean b)
This API can be used to manually generate a bitmap copy of this view, by setting the flag to true and calling
getDrawingCache();
A non-scaled bitmap representing this view or null if cache is disabled
DestoryDrawingCache();
Frees the resources by the drawing cache,if you can call bulidDrawingCache() or setDrawingCacheEnable(true),you should cleanup the cache with this method afterwards.
大概意思就是:我們可以利用它們把view轉化爲Bitmap
下面是我寫的一個小例子:

public Bitmap convertViewToBitmap() {
        TestView.setDrawingCacheEnabled(true);
        TestView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        Bitmap bitmap = TestView.getDrawingCache();
        return bitmap;
    }
 if(item.getItemId()==R.id.action_save_pic){
            Bitmap bitmap = convertViewToBitmap();
            getCommand().savePicture(bitmap);
            TestView.setDrawingCacheEnabled(false);
            TestView.destoryDrawingCache();//這裏記得將緩存銷燬
        }

使用該方法可以將一個佈局轉化爲Bitmap,然後再保存。
*這裏我遇到的一個問題就是按照網絡上的寫法保存了以後佈局會亂跑至左上角,一開始參考網絡上的寫法
網絡上大家提供的方法寫的是:

contentLayout.setDrawingCacheEnabled(true);    

        contentLayout.measure(    

               MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),    

                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));    

       contentLayout.layout(0, 0, contentLayout.getMeasuredWidth(),    

                contentLayout.getMeasuredHeight());    



     contentLayout.buildDrawingCache();    



      Bitmap bitmap= contentLayout.getDrawingCache();   

在使用的時候調用

Bitmap bitmap = view.getDrawingCache();

以上是網絡上的代碼,使用該代碼以後會出現跑到右上角的問題,還有就是我之前在這塊新new 了一個Bitmap來保存緩存的圖片,然後這裏設置了 contentLayout.layout(0, 0, contentLayout.getMeasuredWidth(),contentLayout.getMeasuredHeight()); 這樣使得佈局在左上角顯示。

保存的二維碼圖片一片黑
生成二維碼的代碼:加上如下判斷,意思就是有信息的點顯示黑色,無信息的點顯示白色。另外保存成png默認背景是黑色的,所以會看到一片黑。

 if (resMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;//白色
                    } else {
                        pixels[y * width + x] = 0xffffffff;//黑色
                    }

總結:在遇到需要把佈局截圖保存問題可以使用該方法,自己的理解就是使用了darwingcache以後把View緩存轉化爲了Bitmap,然後我們可以保存該Bitmap.希望能幫助到大家。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章