Android开发之付款码

对于刚完成的付款码模块代码做一个纪录,以备后用。以前做预支付通过Netty框架搭建通信,本次通过轮询任务完成界面刷新。


效果图

知识点

  • 带头像二维码生成

  • 轮询任务

  • 场景动画

  • 旋转动画

生成二维码依赖zxing核心库

compile 'com.google.zxing:core:3.2.1'

网上copy了一份生成带头像二维码的Util类


import android.graphics.Bitmap;
import android.graphics.Canvas;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QRCodeUtil {
    /**
     * 生成二维码Bitmap
     *
     * @param content   内容
     * @param widthPix  图片宽度
     * @param heightPix 图片高度
     * @param logoBm    二维码中心的Logo图标(可以为null)
     * @param filePath  用于存储二维码图片的文件路径
     * @return 生成二维码及保存文件是否成功
     */
    public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
        try {
            if (content == null || "".equals(content)) {
                return false;
            }

            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
//            hints.put(EncodeHintType.MARGIN, 2); //default is 4

            // 图像数据转换,使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法,逐个生成二维码的图片,
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }

            // 生成二维码图片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);

            if (logoBm != null) {
                bitmap = addLogo(bitmap, logoBm);
            }

            //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
            return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 在二维码中间添加Logo图案
     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

}

生成带头像二维码调用实例(耗时操作在非UI线程执行)

 final String filePath = getFileRoot() + File.separator
                + "qr_" + System.currentTimeMillis() + ".jpg";

        //二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean success = QRCodeUtil.createQRImage(content, 800, 800,myApplication.getPhotoBitmap(),filePath);

                if (success) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap resultBitmap = BitmapFactory.decodeFile(filePath);
                            codeImageView.setImageBitmap(resultBitmap);
                        }
                    });
                }
            }
        }).start();

轮训任务每隔5秒刷新金额,每隔1分钟刷新二维码,如果手动刷新了二维码需要重置每隔一分钟刷新二维码的轮训任务。

    Handler handler = new Handler();

    Runnable runnable= new Runnable() {

        @Override
        public void run() {
            requestData();
            handler.postDelayed(this, 5000);
        }
    };

    handler.postDelayed(runnable, 5000);

在销毁当前活动界面注意移除任务

handler.removeCallbacks(runnable);

场景动画是5.0以后的,使用走版本分支(仅5.0+手机支持点击放大,当然还有其他方式可以向下兼容,这里就不提了)

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            codeImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(xxxx.this, codeImageView, "image");
                    ActivityCompat.startActivity(xxxthis, new Intent(xxx.this, xxxxx.class), compat.toBundle());
                }
            });
        }
        //......................................

ViewCompat.setTransitionName(codeImageView, "image");

如果你对场景动画还不太熟悉,可以参考博客

// http://blog.csdn.net/analyzesystem/article/details/51271941

图片旋转转圈就更简单了,多种实现方案我采用的是ObjectAnimator

 private void startRefreshAnimation() {
        //TODO 不停旋转图片
        textView.setText("正在刷新..");
        LinearInterpolator interpolator = new LinearInterpolator();
        refreshAnim = ObjectAnimator.ofFloat(refreshCode, "rotation", 0F, 360F);
        refreshAnim.setRepeatCount(-1);
        refreshAnim.setDuration(1000);
        refreshAnim.setInterpolator(interpolator);
        refreshAnim.start();
    }

 private void stopRefreshAnimation() {
        //TODO 停止旋转图片
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshAnim.end();
                textView.setText("点击刷新二维码");
            }
        },500);
    }

在开发上图效果遇到一个坑,集成一个开源的二维码头像库,生成了带头像的二维码却无法扫描识别,最令人想不通的是这个库有几千start,看评论有好多好多好多bug,小生只想知道这些star怎么来的?

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值