layout轉(zhuǎn)Bitmap

業(yè)務(wù)需求詳細(xì)描述:最近產(chǎn)品說(shuō)要在分享的商品圖中添加一些其他圖片和文字,然后拼接為一張圖片,再分享到微信朋友圈,于是我就一臉懵逼了,但是沒(méi)辦法還是得做額!

然后整理了一下思路,主要有這么兩條路線:

  1. 自己手動(dòng)繪制。
  2. 將布局轉(zhuǎn)換為圖片。

很顯然第一種方式是不合適的,無(wú)論是開發(fā)前還是開發(fā)后,成本都很大,所以果斷選擇了第二種方式。

一開始的時(shí)候,我沒(méi)有經(jīng)過(guò)大腦思考,果斷的使用了getDrawingCache這個(gè)方法來(lái)解決這個(gè)業(yè)務(wù)需求,大致流程如下:

(1)創(chuàng)建需要顯示成圖片的布局,代碼如下:

<?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="長(zhǎng)按識(shí)別二維碼或掃一掃購(gòu)買\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)設(shè)置圖片和文字信息,這里為了方便,直接把文字放到了布局中,設(shè)置圖片的代碼如下所示:

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)然后就可以將布局轉(zhuǎn)換成圖片了,代碼如下所示:

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)然后發(fā)現(xiàn)圖片不能正確顯示,經(jīng)過(guò)debug之后發(fā)現(xiàn)原來(lái)是圖片過(guò)大的緣故,一臉懵逼,雖然使用了這樣的壓縮算法,但總是不盡如人意:

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;
    }
    // 計(jì)算縮放比例
    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;
}

之后有了大神的幫助,終于頓悟了,發(fā)現(xiàn)了神奇的方法:view.draw(canvas)。然后就很簡(jiǎn)單了:
這里的第1步和第2步流程與上面的1、2步流程一模一樣,我們直接進(jìn)入第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)然后將該布局添加到主界面中,并設(shè)置為invisible,但不能設(shè)置為gone,否則不能成功渲染,同樣不能生成圖片了:

mainContent.addView(v);

(4)最后我們就可以在點(diǎn)擊事件里面將布局生成圖片了,代碼如下:

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);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容