android異步生成圖片的示例代碼
下面來說說在Android上如果異步生成圖片,通過xml布局用View排版好圖片樣式,在子線程生成一張圖片,以滿足生成用來分享的圖片等需求(生成圖片前設(shè)置可變元素,如用戶的頭像,昵稱等)。
效果
點擊按鈕生成圖片:
特性
- 通過布局和View的方式設(shè)計圖片樣式。
- 在子線程中生成和保存圖片。
- 封裝好工具類,直接使用即可。
核心代碼
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保存在文件或顯示到界面上。
- 在布局中寫好圖片的樣子,然后把布局inflate成View,當然也可以直接代碼編寫View,設(shè)置好里面的可變元素,如頭像,昵稱等。
- 通過調(diào)用View的measure,layout方法使之測量出內(nèi)部各控件的大小和排列好各控件。
- 創(chuàng)建一個和View大小相同的空Bitmap,新建一個畫布傳入該bitamp(new Canvas(bitmap)),調(diào)用view的draw(canvas)方法,view會把圖片繪制在該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,設(shè)置可變元素并使用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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android關(guān)于獲取時間的記錄(小結(jié))
這篇文章主要介紹了Android關(guān)于獲取時間的記錄(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04android通過gps獲取定位的位置數(shù)據(jù)和gps經(jīng)緯度
這篇文章主要介紹了android通過gps獲取定位的位置數(shù)據(jù)示例,大家參考使用吧2014-01-01