下面来说说在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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。