QRコードを表示する簡単なアプリ


お仕事の中で、QRコードを表示する必要がありiPhoneで動くオープンソースGPLではないQRコード作成ソフトを探したのですが見つからなかったので作ってみました。















まずQRコード作成ライブラリーですが、GPLで無いものということで Rubyrqr で使われている フリーソフト -> QR Code Image | Psytec を使わせて頂きました。また、win2ansi.h は rqrの物を改造して使っています。ありがとうございます。

Objective-C から QR Code Imageを呼び出す QREncodeUIImage

QREncodeUIImage は QR Code Image(QR_Encode.cpp) にQRコード化する文字列を渡し、結果のQRコード画像を UIImage で戻します。

QREncodeUIImage.h

#import <Foundation/Foundation.h>

@interface QREncodeUIImage : NSObject {
}

+ (UIImage *) qrEncodeImageOfText:(NSString *)text;

@end

QREncodeUIImage.mm (C++ コードなので 拡張子を .mm にして下さい)

#import "QREncodeUIImage.h"
#import "QR_Encode.h"

@implementation QREncodeUIImage


+ (UIImage *) qrEncodeImageOfText:(NSString *)text {
	int scale = 4;
	CQR_Encode *qr = new CQR_Encode;
	qr->EncodeData(1, 0, TRUE, -1, (char *)[text UTF8String], 0);
	
	int qr_dots = qr->m_nSymbleSize;
	UIGraphicsBeginImageContext(CGSizeMake(qr_dots * scale, qr_dots * scale));
	CGContextRef imgContext = UIGraphicsGetCurrentContext();
	CGContextSetFillColorWithColor(imgContext, [UIColor whiteColor].CGColor);
	CGContextFillRect(imgContext, CGRectMake(0, 0, qr_dots * scale, qr_dots * scale));
	CGContextSetFillColorWithColor(imgContext, [UIColor blackColor].CGColor);
	for (int y = 0; y < qr_dots; y++) {
		for (int x = 0; x < qr_dots; x++) {
			if (qr->m_byModuleData[x][y]) {
				CGContextFillRect(imgContext, CGRectMake(x * scale, y * scale, scale, scale));
			}
		}
	}
	UIImage *image = [UIImage imageWithCGImage: CGBitmapContextCreateImage(imgContext)];
	UIGraphicsEndImageContext();
	delete qr;
	
	return image;
}

win2ansi.h はそのままではエラーになったので修正しました。QR_Encode.cpp,QR_Encode.h はSJISからUTF-8にコードを変換したでけで変更はしていません。

#ifndef __WIN32_TO_ANSI__
#define __WIN32_TO_ANSI__

#include <string.h>
#include <stdlib.h>

#ifndef TRUE
#define TRUE  true
#define FALSE false
typedef signed char    BOOL;
#endif

typedef unsigned char   BYTE;
typedef unsigned short  WORD;
typedef char*           LPCSTR;
typedef unsigned char * LPBYTE;

#define lstrlen strlen
#define ZeroMemory(x, y) memset(x, 0, y)
#define min(x, y) x < y ? x : y

#endif

テスト アプリ

QREncodeUIImage を使う上の画像のアプリのコード

QREncodeViewController.h

#import <UIKit/UIKit.h>

@interface QREncodeViewController : UIViewController <UITextFieldDelegate> {
	IBOutlet UITextField *encodeTextField;
	IBOutlet UIImageView *imageView;
}
@end

QREncodeViewController.m (一部)

#import "QREncodeViewController.h"
#import "QREncodeUIImage.h"

@implementation QREncodeViewController

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

	imageView.image = [QREncodeUIImage qrEncodeImageOfText:textField.text];

	[textField resignFirstResponder];
	return YES;
}

プロジェクト