목적 : ZXing 라이브러리 사용하여 바코드 생성하기
1. 라이브러리 추가
compile 'com.google.zxing:core:3.3.2'
2. 핵심 코드
// 배경 색상
private static final int WHITE = 0xFFFFFFFF;
// 바코드 색상
private static final int BLACK = 0xFF000000;
private Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
3. 사용법
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView barcode = findViewById(R.id.imageView);
String barcode_data = "1234567890";
// barcode image
try {
Bitmap bitmap = encodeAsBitmap(barcode_data , BarcodeFormat.CODE_128 , 600 , 300);
barcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
도움이 되시면 좋겠습니다.