LoginSignup
8
4

More than 5 years have passed since last update.

ロゴ入りQRコードの生成方法

Last updated at Posted at 2017-04-21

ZXing Android embeddedを入れる

compile 'com.journeyapps:zxing-android-embedded:3.5.0'

そしてこれ。

    private Bitmap createLogoQR(String text, @DrawableRes int drawableId, int width, int height) {
        try {
            BarcodeEncoder encoder = new BarcodeEncoder();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            // 誤り訂正レベルHighで、30%程度QRコードが隠れていても読める
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            Bitmap qr = encoder.encodeBitmap(text, BarcodeFormat.QR_CODE, width, height, hints);

            Bitmap logo = ((BitmapDrawable) ContextCompat.getDrawable(this, drawableId)).getBitmap();

            Bitmap logoQr = Bitmap.createBitmap(qr.getWidth(), qr.getHeight(), qr.getConfig());
            Canvas canvas = new Canvas(logoQr);
            canvas.drawBitmap(qr, new Matrix(), null);

            // 縦横30%程度のサイズにロゴを縮小する
            int scaledLogoWidth = (int)(qr.getWidth() * 0.3f);
            int scaledLogoHeight = (int)(qr.getHeight() * 0.3f);
            Bitmap scaledLogo = Bitmap.createScaledBitmap(logo, scaledLogoWidth, scaledLogoHeight, true);

            float cx = (qr.getWidth() - scaledLogoWidth) / 2.0f;
            float cy = (qr.getHeight() - scaledLogoHeight) / 2.0f;
            canvas.drawBitmap(scaledLogo, cx, cy, null);

            return logoQr;

        } catch (WriterException e) {
            // コンテンツがエンコードできなかった場合
            e.printStackTrace();
        }
        return null;
    }
8
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4