AndroidでQRコード作成

WEBサービスでバーコード作成をしてくれるサービスを利用し、バーコードを作成したときのこと。。。
Androidアプリで同じことができるんじゃって思ってしまった。
WEBサービスと同じバーコードじゃ面白くないから、せっかくなのでQRコードを作成してみました。
その時の備忘録として記事を書いていきたいと思います。




メイン画面
f:id:nlinks:20151208181958p:plain

処理終了後
f:id:nlinks:20151208182022p:plain

QRコードを0から作るのは、さすがに厳しいので、「ZXing」というライブラリを利用させてもらいました。
Android Studioで開発する場合は、Gradleのdependenciesに以下を追加するだけで利用可能になります。

compile 'com.journeyapps:zxing-android-embedded:2.0.1@aar'
compile 'com.journeyapps:zxing-android-legacy:2.0.1@aar'
compile 'com.journeyapps:zxing-android-integration:2.0.1@aar'
compile 'com.google.zxing:core:3.0.1'

① まずはメイン画面を作成します。画面はボタンと結果を表示するためのImageViewで構成します。

 1)レイアウトファイル(fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Create QR Code"
            android:id="@+id/button"
            android:gravity="center"
            android:onClick="onClickQRCodeCreate" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_gravity="center"
            android:layout_marginTop="20dp" />
    </LinearLayout>
</RelativeLayout>

 2)MainActivity.java

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //QRCode作成
    public void onClickQRCodeCreate(View view)
    {
        // QRCodeの作成
        Bitmap qrCodeBitmap = this.createQRCode("http://nlinks-engineers.hatenablog.com/");

        // QRCodeの作成に成功した場合
        if (qrCodeBitmap != null)
        {
            // 結果をImageViewに表示
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(qrCodeBitmap);
        }
    }

    private Bitmap createQRCode(String contents)
    {
        Bitmap qrBitmap = null;
        try {
            // QRコードの生成
            QRCodeWriter qrcodewriter = new QRCodeWriter();
            BitMatrix qrBitMatrix = qrcodewriter.encode(contents,
                                                        BarcodeFormat.QR_CODE,
                                                        300,
                                                        300);

            qrBitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
            qrBitmap.setPixels(this.createDot(qrBitMatrix), 0, 300, 0, 0, 300, 300);
        }
        catch(Exception ex)
        {
            // エンコード失敗
            Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
        }
        finally
        {
            return qrBitmap;
        }
    }

    // ドット単位の判定
    private int[] createDot(BitMatrix qrBitMatrix)
    {
        // 縦幅・横幅の取得
        int width = qrBitMatrix.getWidth();
        int height = qrBitMatrix.getHeight();
        // 枠の生成
        int[] pixels = new int[width * height];

        // データが存在するところを黒にする
        for (int y = 0; y < height; y++)
        {
            // ループ回数盤目のOffsetの取得
            int offset = y * width;
            for (int x = 0; x < width; x++)
            {
                // データが存在する場合
                if (qrBitMatrix.get(x, y))
                {
                    pixels[offset + x] = Color.BLACK;
                }
                else
                {
                    pixels[offset + x] = Color.WHITE;
                }
            }
        }
        // 結果を返す
        return pixels;
    }
}


作りは単純で、「ZXing」の「QRCodeWriter」クラスを利用して、「BitMatrix」を生成し、
内容を解析して、Bitmapを作成しています。
こんなにお手軽にQRコードが作成できるなんて思っていなかったので、びっくりです。
QRコードを作成することなんかないかもしれませんが、どこかで役に立つかもしれないので。。。。
是非とも挑戦してみてください。
ちなみに、今回作成したQRコードは、QRコードリーダーで読み取るとこのブログのUrlになります。
過去の記事も是非とも見てみてください。