layout转Bitmap

链式极昼
• 阅读 5047

业务需求详细描述:最近产品说要在分享的商品图中添加一些其他图片和文字,然后拼接为一张图片,再分享到微信朋友圈,于是我就一脸懵逼了,但是没办法还是得做额!

然后整理了一下思路,主要有这么两条路线:

  1. 自己手动绘制。

  2. 将布局转换为图片。

很显然第一种方式是不合适的,无论是开发前还是开发后,成本都很大,所以果断选择了第二种方式。

一开始的时候,我没有经过大脑思考,果断的使用了getDrawingCache这个方法来解决这个业务需求,大致流程如下:

(1)创建需要显示成图片的布局,代码如下:

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/white">

        <ImageView
            android:id="@+id/img_shop"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dp" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="20dp">

            <ImageView
                android:id="@+id/img_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

            <TextView
                android:id="@+id/txt_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

        </RelativeLayout>

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">

        <ImageView
            android:id="@+id/img_qrcode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="黄老五 提子味皇式烤芙条 300g 沙琪玛 休闲办公室零食...\n"
                android:textColor="@android:color/black" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="长按识别二维码或扫一扫购买\n"
                android:textColor="@android:color/darker_gray" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="From 萌店"
                android:textColor="@android:color/darker_gray" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

(2)设置图片和文字信息,这里为了方便,直接把文字放到了布局中,设置图片的代码如下所示:

private void addLinearLayout() {
    view = View.inflate(this, R.layout.activity_picmontage, null);

    LinearLayout picmontageRoot = (LinearLayout) view.findViewById(R.id.picmontage_root);
    ImageView shopImg = (ImageView) view.findViewById(R.id.img_shop);
    ImageView priceImg = (ImageView) view.findViewById(R.id.img_price);
    TextView priceTxt = (TextView) view.findViewById(R.id.txt_price);
    ImageView qrcodeImg = (ImageView) view.findViewById(R.id.img_qrcode);

    shopImg.setImageResource(R.mipmap.shop);
    priceImg.setImageResource(R.mipmap.price);
    priceTxt.setText("$ 20.00");
    priceTxt.setTextSize(20);
    priceTxt.setTextColor(Color.WHITE);
    qrcodeImg.setImageResource(R.mipmap.qrcode);

    addViewContent.addView(view);
}

(3)然后就可以将布局转换成图片了,代码如下所示:

private void drawingCacheShow() {
    Bitmap cacheBitmap = convertViewToBitmap(addViewContent);
    //Bitmap cacheBitmap = getMagicDrawingCache(addViewContent);

    //addViewContent.removeView(view);

    if(cacheBitmap != null) {
        Bitmap newBitmap = Bitmap.createBitmap(cacheBitmap);
        if (newBitmap != null) {
            imgAddViewCache.setImageBitmap(newBitmap);
        } else {
            Log.i("123", "newBitmap=null");
        }
    } else {
        Log.i("123", "cacheBitmap=null");
    }
}
public static Bitmap convertViewToBitmap(View view){
    view.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    view.buildDrawingCache();
    Bitmap bitmap = view.getDrawingCache();

    if (bitmap != null) {
        Bitmap.Config cfg = bitmap.getConfig();
        Log.d("123", "----------------------- cache.getConfig() = " + cfg);
    }

    return bitmap;
}

(4)然后发现图片不能正确显示,经过debug之后发现原来是图片过大的缘故,一脸懵逼,虽然使用了这样的压缩算法,但总是不尽如人意:

private void addLinearLayout() {
    view = View.inflate(this, R.layout.activity_picmontage, null);

    LinearLayout picmontageRoot = (LinearLayout) view.findViewById(R.id.picmontage_root);
    ImageView shopImg = (ImageView) view.findViewById(R.id.img_shop);
    ImageView priceImg = (ImageView) view.findViewById(R.id.img_price);
    TextView priceTxt = (TextView) view.findViewById(R.id.txt_price);
    ImageView qrcodeImg = (ImageView) view.findViewById(R.id.img_qrcode);

    // 压缩shop
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.shop);
    shopImg.setImageBitmap(resizeBm(bitmap, 600));
    priceImg.setImageResource(R.mipmap.price);
    priceTxt.setText("$ 20.00");
    priceTxt.setTextSize(20);
    priceTxt.setTextColor(Color.WHITE);
    qrcodeImg.setImageResource(R.mipmap.qrcode);

    addViewContent.addView(view);
}
private Bitmap resizeBm(Bitmap bitmap, int scaleWidth) {
    // 原始宽高
    float rawWidth = bitmap.getWidth();
    float rawHeight = bitmap.getHeight();
    // 新宽高
    float newWidth = 0;
    float newHeight = 0;
    // 将宽度缩放到scaleWidth
    if(rawWidth>scaleWidth) {
        newWidth = scaleWidth;
        newHeight = rawHeight*(scaleWidth/rawWidth);
    } else {
        newWidth = rawWidth;
        newHeight = rawHeight;
    }
    // 计算缩放比例
    float widthScale = newWidth/rawWidth;
    float heightScale = newHeight/rawHeight;
    Log.i("123", "widthScale="+widthScale+", heightScale="+heightScale);
    // 显示
    Matrix matrix = new Matrix();
    matrix.postScale(widthScale,heightScale);
    Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
    return resizeBmp;
}

之后有了大神的帮助,终于顿悟了,发现了神奇的方法:view.draw(canvas)。然后就很简单了:
这里的第1步和第2步流程与上面的1、2步流程一模一样,我们直接进入第3步,我先给出主界面中的布局:

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="showPic"
                android:text="显示绘制的图片" />

            <ImageView
                android:id="@+id/img"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

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

        </LinearLayout>

    </ScrollView>

</LinearLayout>

(3)然后将该布局添加到主界面中,并设置为invisible,但不能设置为gone,否则不能成功渲染,同样不能生成图片了:

mainContent.addView(v);

(4)最后我们就可以在点击事件里面将布局生成图片了,代码如下:

public void showPic(View view) {
    int width = picmontageRoot.getMeasuredWidth();
    int height = picmontageRoot.getMeasuredHeight();
    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(b);
    picmontageRoot.draw(canvas);
    img.setImageBitmap(b);
}
点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Stella981 Stella981
4年前
Python+Selenium自动化篇
本篇文字主要学习selenium定位页面元素的集中方法,以百度首页为例子。0.元素定位方法主要有:id定位:find\_element\_by\_id('')name定位:find\_element\_by\_name('')class定位:find\_element\_by\_class\_name(''
Easter79 Easter79
4年前
Taro小程序自定义顶部导航栏
微信自带的顶部导航栏是无法支持自定义icon和增加元素的,在开发小程序的时候自带的根本满足不了需求,分享一个封装好的组件,支持自定义icon、扩展dom,适配安卓、ios、h5,全面屏。我用的是京东的Taro多端编译框架写的小程序,原生的也可以适用,用到的微信/taro的api做调整就行,实现效果如下。!在这里插入图片描述(https://i
Stella981 Stella981
4年前
OpenCV检测轮廓极点(Python C++)
    今天分享一个OpenCV检测轮廓极点实例,原图如下,我们需要检测出地图中最大轮廓的上下左右四个极点,并进行标注显示。!(https://oscimg.oschina.net/oscnet/ae374a72c5404b00b0e976e499eedf36.png)    第一步:阈值处理分割出地图轮廓!(ht
Stella981 Stella981
4年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
4年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Stella981 Stella981
4年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
4年前
unity将 -u4E00 这种 编码 转汉字 方法
 unity中直接使用 JsonMapper.ToJson(对象),取到的字符串,里面汉字可能是\\u4E00类似这种其实也不用转,服务器会通过类似fastjson发序列化的方式,将json转对象,获取对象的值就是中文但是有时服务器要求将传参中字符串中类似\\u4E00这种转汉字,就需要下面 publ
Wesley13 Wesley13
4年前
Java多线程导致的的一个事物性问题
业务场景我们现在有一个类似于文件上传的功能,各个子站点接受业务,业务上传文件,各个子站点的文件需要提交到总站点保存,文件是按批次提交到总站点的,也就是说,一个批次下面约有几百个文件。      考虑到白天提交这么多文件会影响到子站点其他系统带宽,我们将分站点的文件提交到总站点这个操作过程独立出来,放到晚上来做,具体时间是晚上7:00到早上7:00。