Android

Android 布局生成图片

2020-07-02  本文已影响0人  W会痛的石头

需求
在项目中需要分享一张图片到微信朋友圈,这张图片是一个布局生成的,且布局是用户不可见的,点击分享直接在后台加载布局生成图片并保存在本地。

实现方式
1.通过布局设计样式及UI。
2.将布局View转化为Bitmap文件。
3.封装保存Bitmap文件的方法。

核心代码
布局生成Bitmap文件

 //将布局转化成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());
              //转化为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的回调才可以。

上一篇 下一篇

猜你喜欢

热点阅读