安卓Zxing的简单使用-(生成二维码与扫一扫)
前言:Zxing -github链接:https://github.com/zxing/zxing
1、效果图:
zxing自带扫码界面(横屏)
自定义扫码界面
2、
build.gradle中加入
implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
3、MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView;
private TextView textView;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = this.findViewById(R.id.imageView_zxing);
textView = this.findViewById(R.id.textview_zxing);
editText = this.findViewById(R.id.edittext_zxing);
findViewById(R.id.button_zxing).setOnClickListener(this);
findViewById(R.id.button_start).setOnClickListener(this);
findViewById(R.id.button_native).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_zxing:
String count = editText.getText().toString().trim();
if (TextUtils.isEmpty(count)) {
Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_LONG).show();
return;
}
//生成二维码显示在imageView上
imageView.setImageBitmap(generateBitmap(count, 600, 600));
break;
case R.id.button_start:
new IntentIntegrator(this)
.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选:一维码,二维码,一/二维码
//.setPrompt("请对准二维码")// 设置提示语
.setCameraId(0)// 选择摄像头,可使用前置或者后置
.setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
.initiateScan();// 初始化扫码
break;
case R.id.button_native:
new IntentIntegrator(this)
.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选:一维码,二维码,一/二维码
//.setPrompt("请对准二维码")// 设置提示语
.setCameraId(0)// 选择摄像头,可使用前置或者后置
.setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
.setCaptureActivity(QrCodeActivity.class)//自定义扫码界面
.initiateScan();// 初始化扫码
break;
}
}
/**
* 生成固定大小的二维码(不需网络权限)
*
* @param content 需要生成的内容
* @param width 二维码宽度
* @param height 二维码高度
* @return
*/
private Bitmap generateBitmap(String content, int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//扫码结果
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
if (intentResult.getContents() == null) {
//扫码失败
} else {
String result = intentResult.getContents();//返回值
textView.setText("扫码结果:" + result);
}
}
}
}
CustomZxingView自定义扫码View
public class CustomZxingView extends ViewfinderView {
public int laserLinePosition = 0;
public float[] position = new float[]{0f, 0.5f, 1f};
public int[] colors = new int[]{0xff0699e6, 0xff0699e6, 0xff0699e6};
public LinearGradient linearGradient;
public CustomZxingView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 重写draw方法绘制自己的扫描框
*
* @param canvas
*/
@Override
public void onDraw(Canvas canvas) {
refreshSizes();
if (framingRect == null || previewFramingRect == null) {
return;
}
Rect frame = framingRect;
Rect previewFrame = previewFramingRect;
int width = canvas.getWidth();
int height = canvas.getHeight();
//绘制4个角
paint.setColor(Color.parseColor("#139D57"));//定义画笔的颜色
canvas.drawRect(frame.left, frame.top, frame.left + 100, frame.top + 10, paint);
canvas.drawRect(frame.left, frame.top, frame.left + 10, frame.top + 100, paint);
canvas.drawRect(frame.right - 100, frame.top, frame.right, frame.top + 10, paint);
canvas.drawRect(frame.right - 10, frame.top, frame.right, frame.top + 100, paint);
canvas.drawRect(frame.left, frame.bottom - 10, frame.left + 100, frame.bottom, paint);
canvas.drawRect(frame.left, frame.bottom - 100, frame.left + 10, frame.bottom, paint);
canvas.drawRect(frame.right - 100, frame.bottom - 10, frame.right, frame.bottom, paint);
canvas.drawRect(frame.right - 10, frame.bottom - 100, frame.right, frame.bottom, paint);
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
int middle = frame.height() / 2 + frame.top;
laserLinePosition = laserLinePosition + 5;
if (laserLinePosition > frame.height()) {
laserLinePosition = 0;
}
linearGradient = new LinearGradient(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, colors, position, Shader.TileMode.CLAMP);
// Draw a red "laser scanner" line through the middle to show decoding is active
paint.setShader(linearGradient);
//绘制扫描线
canvas.drawRect(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, paint);
paint.setShader(null);
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
float radius = POINT_SIZE / 2.0f;
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
radius, paint);
}
}
postInvalidateDelayed(16,
frame.left,
frame.top,
frame.right,
frame.bottom);
}
}
}
QrCodeActivity:
public class QrCodeActivity extends AppCompatActivity implements DecoratedBarcodeView.TorchListener {
private DecoratedBarcodeView decoratedBarcodeView;
private CaptureManager captureManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_code);
decoratedBarcodeView=this.findViewById(R.id.decoratedBarcodeView);
//重要代码,初始化捕获
captureManager = new CaptureManager(this, decoratedBarcodeView);
captureManager.initializeFromIntent(getIntent(), savedInstanceState);
captureManager.decode();
decoratedBarcodeView.setTorchListener(this);
}
@Override
public void onTorchOn() {
}
@Override
public void onTorchOff() {
}
@Override
protected void onPause() {
super.onPause();
captureManager.onPause();
}
@Override
protected void onResume() {
super.onResume();
captureManager.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
captureManager.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
captureManager.onSaveInstanceState(outState);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return decoratedBarcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
}
4、布局文件
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:padding="5dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edittext_zxing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入需要生成二维码的内容" />
<Button
android:id="@+id/button_zxing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="生成二维码" />
<ImageView
android:id="@+id/imageView_zxing"
android:layout_width="match_parent"
android:layout_height="250dp" />
<Button
android:id="@+id/button_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启扫一扫(zxing自带扫码界面)" />
<Button
android:layout_marginTop="10dp"
android:id="@+id/button_native"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启扫一扫(自定义扫码界面)" />
<TextView
android:id="@+id/textview_zxing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="扫码的结果" />
</LinearLayout>
activity_qr_code.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="@+id/decoratedBarcodeView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_framing_rect_height="250dp"
app:zxing_framing_rect_width="250dp"
app:zxing_preview_scaling_strategy="fitXY"
app:zxing_scanner_layout="@layout/layout_zxing"
app:zxing_use_texture_view="true" />
</LinearLayout>
layout_zxing.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.journeyapps.barcodescanner.BarcodeView
android:id="@+id/zxing_barcode_surface"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_framing_rect_height="300dp"
app:zxing_framing_rect_width="300dp" />
<com.helloworld.zxingdemo.CustomZxingView
android:id="@+id/zxing_viewfinder_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_possible_result_points="#139D57"
app:zxing_result_view="@color/zxing_custom_result_view"
app:zxing_viewfinder_laser="#fff"
app:zxing_viewfinder_mask="#60000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="20dp"
android:text="请对准二维码开始扫描"
android:textColor="#fff" />
</merge>