layout轉Bitmap

業務需求詳細描述:最近產品說要在分享的商品圖中添加一些其餘圖片和文字,而後拼接爲一張圖片,再分享到微信朋友圈,因而我就一臉懵逼了,可是沒辦法仍是得作額!java

而後整理了一下思路,主要有這麼兩條路線:android

  1. 本身手動繪製。算法

  2. 將佈局轉換爲圖片。canvas

很顯然第一種方式是不合適的,不管是開發前仍是開發後,成本都很大,因此果斷選擇了第二種方式。bash

一開始的時候,我沒有通過大腦思考,果斷的使用了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)設置圖片和文字信息,這裏爲了方便,直接把文字放到了佈局中,設置圖片的代碼以下所示:post

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)而後就能夠將佈局轉換成圖片了,代碼以下所示:ui

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以後發現原來是圖片過大的緣故,一臉懵逼,雖然使用了這樣的壓縮算法,但老是不盡如人意:this

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步流程與上面的一、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);
}
相關文章
相關標籤/搜索