下面來說說在Android上如果異步生成圖片,通過xml布局用View排版好圖片樣式,在子線程生成一張圖片,以滿足生成用來分享的圖片等需求(生成圖片前設置可變元素,如用戶的頭像,昵稱等)。
效果
點擊按鈕生成圖片:

特性
核心代碼
private Bitmap createBitmap(View view) { int widthSpec = View.MeasureSpec.makeMeasureSpec(view.getLayoutParams().width, View.MeasureSpec.EXACTLY); int heightSpec = View.MeasureSpec.makeMeasureSpec(view.getLayoutParams().height, View.MeasureSpec.EXACTLY); view.measure(widthSpec, heightSpec); int measureWidth = view.getMeasuredWidth(); int measureHeight = view.getMeasuredHeight(); view.layout(0, 0, measureWidth, measureHeight); int width = view.getWidth(); int height = view.getHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return bitmap; }原理說明
通過走一遍ViewGroup的測量(measure),布局(layout),draw流程,把布局展示的界面畫到我們準備好的bitmap上(這一過程可在非UI線程完成),再把bitmap保存在文件或顯示到界面上。
使用方法
在xml中布局圖片樣式:
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="200dp" android:layout_height="200dp" android:background="#ECAA0A"> <ImageView android:layout_width="160dp" android:layout_height="94dp" android:layout_gravity="center_horizontal" android:src="@mipmap/pic_bg" /> <ImageView android:id="@+id/invitation_share_link_pic_avatar_iv" android:layout_width="80dp" android:layout_height="80dp" android:layout_gravity="center_horizontal|bottom" android:layout_marginBottom="10dp" android:src="@mipmap/ic_launcher" /></FrameLayout>
寫一個自己的Model繼承自GenerateModel,設置可變元素并使用GeneratePictureManager單例的generate方法開始生成:
private void generate() { SharePicModel sharePicModel = new SharePicModel((ViewGroup) getWindow().getDecorView()); sharePicModel.setAvatarResId(R.mipmap.ic_launcher); GeneratePictureManager.getInstance().generate(sharePicModel, (throwable, bitmap) -> { if (throwable != null || bitmap == null) { Toast.makeText(this, getString(R.string.generate_pic_error), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.generate_pic_success), Toast.LENGTH_SHORT).show(); mResultIv.setImageBitmap(bitmap); } }); }源碼地址Github: https://github.com/homgwu/picgenerator
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答