Android studio 二维码开源项目ZXing使用详解
来源:互联网 发布:mac关闭页面快捷键 编辑:程序博客网 时间:2024/05/17 08:26
ZXing的github
https://github.com/zxing/zxing
ZXing的库很大。但是我们需要的只有以下三个
首先新建一个Project,将android(Eclipse 工程) 导入到Project中,并改为library(鹅,不会的百度),直接导入是会报错的,因为缺少一些东西,把刚android-studio中的CameraConfigurationUtils.java也加入到导入的module。
接着就是core的jar包
引用 :Android Studio生成自定义jar包
新建一个library的module,将core中的代码拷贝进去,然后在gradle文件中配置
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0'} def SDK_BASENAME = "TestSdk";def SDK_VERSION = "_V1.0";def sdkDestinationPath = "build";def zipFile = file('build/intermediates/bundles/release/classes.jar') task deleteBuild(type: Delete) { delete sdkDestinationPath + SDK_BASENAME + SDK_VERSION + ".jar"} task makeJar(type: Jar) { from zipTree(zipFile) from fileTree(dir: 'src/main',includes: ['assets/**']) baseName = SDK_BASENAME + SDK_VERSION destinationDir = file(sdkDestinationPath)} makeJar.dependsOn(deleteBuild, build)
SDK_BASENAME = "TestSdk";SDK_VERSION = "_V1.0"; 是定义生成jar的名字为TestSdk_V1.0.ja
接着打开studo的gradle视图,core->tast->other->makejar,运行makejar任务
成功后就生成了所需要的jar包,将jar放入到android的libs下
然后就是把剩下的错误改掉,就不详细说了
界面定制
引用:
链接1
链接2
CaptureActivity
ZXing暴露的调用Activity。在handleDecode方法中对扫码成功后的动作作处理。
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); String resultString = rawResult.getText(); if (resultString.equals("")) { Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show(); }else { Intent resultIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("result", resultString); bundle.putParcelable("bitmap", barcode); resultIntent.putExtras(bundle); this.setResult(RESULT_OK, resultIntent); } finish(); }
ViewfinderView
ZXing扫码窗口的绘制,原始的ZXing使用这种方式去绘制。我就直接引用别人定制的代码。
public final class ViewfinderView extends View { private static final String TAG = "log"; /** * 刷新界面的时间 */ private static final long ANIMATION_DELAY = 10L; private static final int OPAQUE = 0xFF; /** * 四个绿色边角对应的长度 */ private int ScreenRate; /** * 四个绿色边角对应的宽度 */ private static final int CORNER_WIDTH = 10; /** * 扫描框中的中间线的宽度 */ private static final int MIDDLE_LINE_WIDTH = 6; /** * 扫描框中的中间线的与扫描框左右的间隙 */ private static final int MIDDLE_LINE_PADDING = 5; /** * 中间那条线每次刷新移动的距离 */ private static final int SPEEN_DISTANCE = 5; /** * 手机的屏幕密度 */ private static float density; /** * 字体大小 */ private static final int TEXT_SIZE = 16; /** * 字体距离扫描框下面的距离 */ private static final int TEXT_PADDING_TOP = 30; /** * 画笔对象的引用 */ private Paint paint; /** * 中间滑动线的最顶端位置 */ private int slideTop; /** * 中间滑动线的最底端位置 */ private int slideBottom; private Bitmap resultBitmap; private final int maskColor; private final int resultColor; private final int resultPointColor; private Collection<ResultPoint> possibleResultPoints; private Collection<ResultPoint> lastPossibleResultPoints; boolean isFirst; private CameraManager cameraManager; public ViewfinderView(Context context, AttributeSet attrs) { super(context, attrs); density = context.getResources().getDisplayMetrics().density; //将像素转换成dp ScreenRate = (int)(20 * density); paint = new Paint(); Resources resources = getResources(); maskColor = resources.getColor(R.color.viewfinder_mask); resultColor = resources.getColor(R.color.result_view); resultPointColor = resources.getColor(R.color.possible_result_points); possibleResultPoints = new HashSet<ResultPoint>(5); } public void setCameraManager(CameraManager cameraManager) { this.cameraManager = cameraManager; } @Override public void onDraw(Canvas canvas) { //中间的扫描框,你要修改扫描框的大小,去CameraManager里面修改 Rect frame = cameraManager.getFramingRect(); if (frame == null) { return; } //初始化中间线滑动的最上边和最下边 if(!isFirst){ isFirst = true; slideTop = frame.top; slideBottom = frame.bottom; } //获取屏幕的宽和高 int width = canvas.getWidth(); int height = canvas.getHeight(); 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(OPAQUE); canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint); } else { //画扫描框边上的角,总共8个部分 paint.setColor(Color.GREEN); canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top + ScreenRate, paint); canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top + ScreenRate, paint); canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left + ScreenRate, frame.bottom, paint); canvas.drawRect(frame.left, frame.bottom - ScreenRate, frame.left + CORNER_WIDTH, frame.bottom, paint); canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH, frame.right, frame.bottom, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate, frame.right, frame.bottom, paint); //绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE slideTop += SPEEN_DISTANCE; if(slideTop >= frame.bottom){ slideTop = frame.top; } canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint); //画扫描框下面的字 paint.setColor(Color.WHITE); paint.setTextSize(TEXT_SIZE * density); paint.setAlpha(0x40); paint.setTypeface(Typeface.create("System", Typeface.BOLD)); canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint); Collection<ResultPoint> currentPossible = possibleResultPoints; Collection<ResultPoint> currentLast = lastPossibleResultPoints; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new HashSet<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(OPAQUE); paint.setColor(resultPointColor); for (ResultPoint point : currentPossible) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint); } } if (currentLast != null) { paint.setAlpha(OPAQUE / 2); paint.setColor(resultPointColor); for (ResultPoint point : currentLast) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint); } } //只刷新扫描框的内容,其他地方不刷新 postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); } } public void drawViewfinder() { resultBitmap = null; invalidate(); } /** * Draw a bitmap with the result points highlighted instead of the live * scanning display. * * @param barcode * An image of the decoded barcode. */ public void drawResultBitmap(Bitmap barcode) { resultBitmap = barcode; invalidate(); } public void addPossibleResultPoint(ResultPoint point) { possibleResultPoints.add(point); }}
CameraConfigurationManager
修改横竖屏、处理变形效果的核心类。源码用的是横屏,如果切换竖屏图像会变形。
在public void setDesiredCameraParameters(Camera camera, boolean safeMode)方法可以将扫描改为竖屏:zai
在Log.i(TAG, "Screen resolution in current orientation: " + screenResolution); 后添加
Point screenResolutionForCamera = new Point();screenResolutionForCamera.x = screenResolution.x;screenResolutionForCamera.y = screenResolution.y;if (screenResolution.x < screenResolution.y) { screenResolutionForCamera.x = screenResolution.y; screenResolutionForCamera.y = screenResolution.x;}
然后修改如下代码
cameraResolution = CameraConfigurationUtils.findBestPreviewSizeValue(parameters, screenResolutionForCamera);bestPreviewSize = CameraConfigurationUtils.findBestPreviewSizeValue(parameters, screenResolutionForCamera);
EncodeingUtils.java 将文字转换为二维码的工具类
public class EncodingUtils { public static final Bitmap createQRCode(String contentsToEncode,int dimension) { if (contentsToEncode == null) { return null; } Map<EncodeHintType, Object> hints = null; String encoding = guessAppropriateEncoding(contentsToEncode); if (encoding != null) { hints = new EnumMap<>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, encoding); } BitMatrix result; try { BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE; result = new MultiFormatWriter().encode(contentsToEncode, barcodeFormat, dimension, dimension, hints); } catch (Exception 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; }}
还有些细节上的调整就不说了,自己看看也能搞定了.
接着就是例子了
<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" > <Button android:onClick="scan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始扫描" /> <TextView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="wrap_content"/> <EditText android:id="@+id/input" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入要编码的内容"/> <Button android:onClick="gene" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="生成二维码"/> <ImageView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"/></LinearLayout>
public class MainActivity extends AppCompatActivity { private TextView tvShow; private EditText etInput; private ImageView ivQR; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvShow = (TextView) findViewById(R.id.show); etInput = (EditText) findViewById(R.id.input); ivQR = (ImageView) findViewById(R.id.iv); } public void scan(View view){ Toast.makeText(this, "可以开始扫描", Toast.LENGTH_SHORT).show(); Intent intent=new Intent(); intent.setClass(this, CaptureActivity.class); startActivityForResult(intent,0); } public void gene(View view){ String input=etInput.getText().toString(); if (TextUtils.isEmpty(input)) { } else { try { Bitmap qrCode = EncodingUtils.createQRCode(input,400); ivQR.setImageBitmap(qrCode); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode==RESULT_OK) { String result=data.getStringExtra("result"); tvShow.setText(result); } }
最后附上github地址
https://github.com/keroro2015/ZXing
- Android studio 二维码开源项目ZXing使用详解
- Android 二维码ZXing使用详解
- Android二维码开源项目zxing编译
- Android二维码开源项目zxing编译
- Android Studio 使用zxing二维码处理
- Zxing二维码开源项目
- (android 开源项目)二维码、条形码扫描——使用Google ZXing .
- Android二维码识别 开源项目ZXing的编译
- Android二维码识别 开源项目ZXing的编译
- android二维码开源项目zxing编译 命令行编译
- Android studio 使用Zxing二维码扫描,过程及问题汇总
- Android studio 使用Zxing二维码扫描,过程及问题汇总
- ZXing二维码开源项目,横屏变竖屏
- Android二维码开源项目zxing用例简化和生成二维码、条形码
- 【ZXing】Android使用zxing生成二维码图片
- Android 使用Zxing生成二维码
- Android二维码工具zxing使用
- Android Studio 导入zxing项目
- FastDFS之添加机器同步
- shell 二维数组
- pdb
- fastclick.js插件使用简单说明
- 整理
- Android studio 二维码开源项目ZXing使用详解
- 圣诞虽好,可别忘了背后的一些数据!
- 机器学习(八):AnomalyDetection异常检测_Python
- 鹏哥yh搜索
- LVS:三种负载均衡方式比较
- 客户管理系统的增删改查
- 随便写点日记
- js 截取url?后参数方法(允许带默认参数)
- Android下拉刷新上拉加载记录