Android 布局生成圖片

需求
在項目中需要分享一張圖片到微信朋友圈,這張圖片是一個布局生成的,且布局是用戶不可見的,點擊分享直接在后臺加載布局生成圖片并保存在本地。

實現(xiàn)方式
1.通過布局設計樣式及UI。
2.將布局View轉(zhuǎn)化為Bitmap文件。
3.封裝保存Bitmap文件的方法。

核心代碼
布局生成Bitmap文件

 //將布局轉(zhuǎn)化成view對象
houseShareInflater = getLayoutInflater().inflate(R.layout.house_share_posters, null);     
 Imageview mIvSharePhoto=houseShareInflater .findViewById(R.id.iv_share_posters_house_photo);  
     Glide.with(SecondHouseDetailsActivity.this).asBitmap().load(secondHouseDetailsBeanData.getMeiti().getZhaopian().get(0).getDizhi()) .into(new SimpleTarget<Bitmap>() {
    @Override
     public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
         if (resource != null) {
              mIvSharePhoto.setImageBitmap(resource );
                //打開圖片的緩存
              houseShareInflater.setDrawingCacheEnabled(true);
               //圖片的大小 固定的語句
               houseShareInflater.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
              View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
               //將位置傳給view
               houseShareInflater.layout(0, 0, houseShareInflater.getMeasuredWidth(), houseShareInflater.getMeasuredHeight());
              //轉(zhuǎn)化為bitmap文件
              Bitmap bitmap = houseShareInflater.getDrawingCache();

保存Bitmap文件

public void savePicture(Bitmap bm, String fileName) {
    if (null == bm) {
        Log.i("xing", "savePicture: ------------------圖片為空------");
        return;
    }
    File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/grainimage");
    if (!foder.exists()) {
        foder.mkdirs();
    }
    File myCaptureFile = new File(foder, fileName);
    try {
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        //壓縮保存到本地
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
}

*注意注意

如果布局中有圖片且布局是在后臺生成的,使用Gilde直接加載會導致圖片加載失敗,具體原因還不清楚。要使用Gilde生成Bitmap的回調(diào)才可以。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容