├── app ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── raw │ │ │ └── beep.mp3 │ │ ├── values │ │ │ └── strings.xml │ │ └── layout │ │ │ └── demo.xml │ │ ├── java │ │ └── com │ │ │ └── yeamy │ │ │ └── support │ │ │ └── zxing │ │ │ └── demo │ │ │ ├── ScanResultDialog.java │ │ │ ├── OnFailDialog.java │ │ │ └── DemoActivity.java │ │ └── AndroidManifest.xml ├── build.gradle └── proguard-rules.pro ├── zxing ├── .gitignore ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── yeamy │ │ │ └── support │ │ │ └── zxing │ │ │ ├── CameraShotListener.java │ │ │ ├── ScanResultListener.java │ │ │ ├── Size.java │ │ │ ├── plugin │ │ │ ├── InactivityTimer.java │ │ │ ├── BeepManager.java │ │ │ └── ViewfinderView.java │ │ │ ├── Viewfinder.java │ │ │ ├── LooperThread.java │ │ │ ├── ScanResult.java │ │ │ ├── decode │ │ │ ├── DecodeConfig.java │ │ │ ├── DecodeRequest.java │ │ │ └── DecodeBean.java │ │ │ ├── camera │ │ │ ├── AutoFocusManager.java │ │ │ ├── CameraImpl.java │ │ │ ├── ScanManager.java │ │ │ └── PreviewManager.java │ │ │ └── ZxingSupport.java │ │ ├── AndroidManifest.xml │ │ └── res │ │ └── values │ │ └── viewfinderview.xml ├── build.gradle └── proguard-rules.pro ├── settings.gradle ├── .gitignore ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── README.md ├── gradlew.bat └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /zxing/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':zxing' 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/* 5 | /build 6 | -------------------------------------------------------------------------------- /app/src/main/res/raw/beep.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yeamy/ZxingSupport/HEAD/app/src/main/res/raw/beep.mp3 -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ZxingSupport 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yeamy/ZxingSupport/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/CameraShotListener.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | public interface CameraShotListener { 4 | 5 | void onCameraShot(byte[] data); 6 | } 7 | -------------------------------------------------------------------------------- /zxing/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/ScanResultListener.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | public interface ScanResultListener { 4 | 5 | /** 6 | * 扫描完成 7 | * @param result 扫描结果 8 | */ 9 | void onScanSuccess(ScanResult result); 10 | 11 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jun 04 08:49:50 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/Size.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | public class Size { 4 | public int width; 5 | public int height; 6 | 7 | public Size(int width, int height) { 8 | this.width = width; 9 | this.height = height; 10 | } 11 | 12 | public void rotate() { 13 | int tmp = width; 14 | width = height; 15 | height = tmp; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /zxing/src/main/res/values/viewfinderview.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/yeamy/support/zxing/demo/ScanResultDialog.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.demo; 2 | 3 | 4 | import android.app.AlertDialog; 5 | import android.content.Context; 6 | 7 | /** 8 | * show the Scan Result 9 | */ 10 | public class ScanResultDialog extends AlertDialog.Builder { 11 | 12 | public ScanResultDialog(Context context, String result) { 13 | super(context); 14 | setTitle("The Scan Result is:"); 15 | setMessage(result); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /zxing/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | minSdkVersion 14 7 | targetSdkVersion 28 8 | versionCode 1 9 | versionName "1.0" 10 | } 11 | buildTypes { 12 | release { 13 | minifyEnabled false 14 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 15 | } 16 | } 17 | productFlavors { 18 | } 19 | } 20 | 21 | dependencies { 22 | api fileTree(include: ['*.jar'], dir: 'libs') 23 | api 'com.google.zxing:core:3.3.0' 24 | } 25 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | applicationId "com.yeamy.support.zxing.demo" 7 | minSdkVersion 21 8 | targetSdkVersion 28 9 | versionCode 1 10 | versionName "1.0" 11 | } 12 | buildTypes { 13 | release { 14 | minifyEnabled false 15 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 16 | } 17 | } 18 | productFlavors { 19 | } 20 | } 21 | 22 | dependencies { 23 | api fileTree(include: ['*.jar'], dir: 'libs') 24 | api project(':zxing') 25 | } 26 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Applications/Android_SDK_Manager/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /zxing/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Applications/Android_SDK_Manager/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/plugin/InactivityTimer.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.plugin; 2 | 3 | import android.app.Activity; 4 | 5 | import java.util.Timer; 6 | import java.util.TimerTask; 7 | 8 | /** 9 | * Code come from zxing-android with little modification, can be replay by the original file; 10 | */ 11 | public final class InactivityTimer { 12 | 13 | public static final long INACTIVITY_DELAY_MS = 15 * 60 * 1000L; 14 | 15 | private final Timer timer = new Timer(); 16 | private TimerTask task; 17 | 18 | public void onResume(final Activity activity, long time) { 19 | timer.schedule(task = new TimerTask() { 20 | @Override 21 | public void run() { 22 | activity.finish(); 23 | } 24 | }, time); 25 | } 26 | 27 | public void onPause() { 28 | task.cancel(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 12 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/yeamy/support/zxing/demo/OnFailDialog.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.demo; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog.Builder; 5 | import android.content.DialogInterface; 6 | 7 | public class OnFailDialog extends Builder { 8 | 9 | public OnFailDialog(Activity context) { 10 | super(context); 11 | setTitle(context.getString(R.string.app_name)); 12 | setMessage("Sorry, the Android camera encountered a problem. You may need to restart the device."); 13 | setPositiveButton(android.R.string.ok, new FinishListener(context)); 14 | setOnCancelListener(new FinishListener(context)); 15 | } 16 | 17 | private class FinishListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { 18 | 19 | private final Activity activityToFinish; 20 | 21 | public FinishListener(Activity activityToFinish) { 22 | this.activityToFinish = activityToFinish; 23 | } 24 | 25 | @Override 26 | public void onCancel(DialogInterface dialogInterface) { 27 | run(); 28 | } 29 | 30 | @Override 31 | public void onClick(DialogInterface dialogInterface, int i) { 32 | run(); 33 | } 34 | 35 | private void run() { 36 | activityToFinish.finish(); 37 | } 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/Viewfinder.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | import android.graphics.Rect; 4 | import android.view.TextureView; 5 | 6 | import com.google.zxing.ResultPointCallback; 7 | 8 | public interface Viewfinder extends ResultPointCallback { 9 | public static final int MIN_FRAME_WIDTH = 260; 10 | public static final int MIN_FRAME_HEIGHT = 260; 11 | public static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920 12 | public static final int MAX_FRAME_HEIGHT = 675; // = 5/8 * 1080 13 | public static final int MIN_PREVIEW_PIXELS = 480 * 320; // normal screen 14 | 15 | /** 16 | * the size of the preview surface plan to layout 17 | * 18 | * @return can not be null, 19 | */ 20 | Size getPreviewSize(); 21 | 22 | /** 23 | * preview code has been done, to change the surface size here 24 | * 25 | * @param pw the width of camera preview 26 | * @param ph the height of camera preview 27 | */ 28 | void onStartPreview(TextureView view, int pw, int ph); 29 | 30 | /** 31 | * the viewfinder's size 32 | * 33 | * @return {@link #MIN_FRAME_WIDTH} <= width <= {@link #MAX_FRAME_WIDTH}
34 | * {@link #MIN_FRAME_HEIGHT} <= height <= {@link #MAX_FRAME_HEIGHT} 35 | */ 36 | Rect getFrameRect(); 37 | 38 | /** 39 | * orientation to display camera preview, only support 0 (landspace) or 90 (portrait) so far 40 | * 41 | * @return 0 or 90 42 | */ 43 | int getOrientation(); 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/res/layout/demo.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 15 | 16 | 22 | 23 | 34 | 35 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/LooperThread.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | import android.os.Build; 4 | import android.os.Handler; 5 | import android.os.Looper; 6 | 7 | import java.util.concurrent.CountDownLatch; 8 | 9 | public class LooperThread extends Thread { 10 | private Handler handler; 11 | private CountDownLatch handlerInitLatch; 12 | 13 | public LooperThread() { 14 | handlerInitLatch = new CountDownLatch(1); 15 | } 16 | 17 | private Handler getHandler() { 18 | try { 19 | handlerInitLatch.await(); 20 | } catch (InterruptedException ie) { 21 | // continue? 22 | } 23 | return handler; 24 | } 25 | 26 | @Override 27 | public void run() { 28 | Looper.prepare(); 29 | handler = new Handler(); 30 | handlerInitLatch.countDown(); 31 | Looper.loop(); 32 | } 33 | 34 | public void post(Runnable r) { 35 | getHandler().post(r); 36 | } 37 | 38 | public void postDelayed(Runnable r, long delayMillis) { 39 | getHandler().postDelayed(r, delayMillis); 40 | } 41 | 42 | public void removeCallbacks(Runnable r) { 43 | getHandler().removeCallbacks(r); 44 | } 45 | 46 | public void close() { 47 | post(new Runnable() { 48 | 49 | @Override 50 | public void run() { 51 | Looper looper = Looper.myLooper(); 52 | if (looper != null) { 53 | if (Build.VERSION.SDK_INT >= 18) { 54 | looper.quitSafely(); 55 | } else { 56 | looper.quit(); 57 | } 58 | } 59 | } 60 | }); 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/plugin/BeepManager.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.plugin; 2 | 3 | import android.annotation.TargetApi; 4 | import android.content.Context; 5 | import android.media.AudioAttributes; 6 | import android.media.AudioManager; 7 | import android.media.SoundPool; 8 | import android.os.Build; 9 | 10 | public final class BeepManager { 11 | 12 | private SoundPool soundPool; 13 | private float volume = -1; 14 | private int soundID; 15 | private int resId; 16 | 17 | /** 18 | * @param resId the resource ID of beep 19 | */ 20 | public BeepManager(int resId) { 21 | this.resId = resId; 22 | } 23 | 24 | public void initVolume(Context context) { 25 | if (volume == -1) { 26 | AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 27 | volume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * 0.5f; 28 | } 29 | } 30 | 31 | public void setVolume(float volume) { 32 | this.volume = volume; 33 | } 34 | 35 | @TargetApi(21) 36 | @SuppressWarnings("deprecation") 37 | private SoundPool buildPlayer(Context context) { 38 | initVolume(context); 39 | SoundPool soundPool; 40 | if (Build.VERSION.SDK_INT >= 21) { 41 | SoundPool.Builder builder = new SoundPool.Builder(); 42 | builder.setMaxStreams(1); 43 | AudioAttributes attrs = new AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_MUSIC) 44 | .build(); 45 | builder.setAudioAttributes(attrs); 46 | soundPool = builder.build(); 47 | } else { 48 | soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); 49 | } 50 | soundID = soundPool.load(context, resId, 1); 51 | 52 | return soundPool; 53 | } 54 | 55 | public void onResume(Context context) { 56 | if (soundPool == null) { 57 | // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud, 58 | // so we now play on the music stream. 59 | // activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); 60 | soundPool = buildPlayer(context); 61 | } 62 | } 63 | 64 | public void onPause() { 65 | close(); 66 | } 67 | 68 | public void play() { 69 | if (soundPool != null) { 70 | soundPool.play(soundID, volume, volume, 1, 0, 1); 71 | } 72 | } 73 | 74 | public void close() { 75 | if (soundPool != null) { 76 | soundPool.release(); 77 | soundPool = null; 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/ScanResult.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | import com.google.zxing.BarcodeFormat; 4 | import com.google.zxing.Result; 5 | import com.google.zxing.ResultMetadataType; 6 | import com.google.zxing.client.result.ParsedResult; 7 | import com.google.zxing.client.result.ParsedResultType; 8 | import com.google.zxing.client.result.ResultParser; 9 | 10 | import java.util.Collection; 11 | import java.util.EnumSet; 12 | import java.util.Map; 13 | 14 | public class ScanResult { 15 | 16 | private final String text; 17 | private final String displayContents; 18 | private final ParsedResultType type; 19 | private final BarcodeFormat codeFormat; 20 | private final Map metadata; 21 | 22 | public ScanResult(Result rawResult) { 23 | codeFormat = rawResult.getBarcodeFormat(); 24 | text = rawResult.getText(); 25 | 26 | ParsedResult pasedResult = ResultParser.parseResult(rawResult); 27 | type = pasedResult.getType(); 28 | displayContents = pasedResult.getDisplayResult().replace("\r", ""); 29 | metadata = rawResult.getResultMetadata(); 30 | } 31 | 32 | public String getDisplayContents() { 33 | return displayContents; 34 | } 35 | 36 | public ParsedResultType getType() { 37 | return type; 38 | } 39 | 40 | public String getTypeText() { 41 | return type.toString(); 42 | } 43 | 44 | public BarcodeFormat getFormat() { 45 | return codeFormat; 46 | } 47 | 48 | public String getRawText() { 49 | return text; 50 | } 51 | 52 | public Map getMetadata() { 53 | return metadata; 54 | } 55 | 56 | public CharSequence getMetadataText() { 57 | final Collection DISPLAYABLE_METADATA_TYPES = // 58 | EnumSet.of(ResultMetadataType.ISSUE_NUMBER, // 59 | ResultMetadataType.SUGGESTED_PRICE, // 60 | ResultMetadataType.ERROR_CORRECTION_LEVEL, // 61 | ResultMetadataType.POSSIBLE_COUNTRY); 62 | if (metadata != null) { 63 | StringBuilder metadataText = new StringBuilder(20); 64 | for (Map.Entry entry : metadata.entrySet()) { 65 | if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { 66 | metadataText.append(entry.getValue()).append('\n'); 67 | } 68 | } 69 | if (metadataText.length() > 0) { 70 | metadataText.setLength(metadataText.length() - 1); 71 | return metadataText; 72 | } 73 | } 74 | return null; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zxing Support 2 | 3 | ### 前言 4 | ------ 5 | 目前二维码扫描十分普遍,Android平台上基本使用Zxing二次开发,但是原生Zxing库使用麻烦,该项目为了方便开发者快速使用。 6 | 7 | 本项目目的是为了方便开发者使用Zxing,项目是2015年开始,按照[Zxing官方项目](https://github.com/zxing/zxing)源码修改而来,只引入zxing core解析库。 8 | 9 | 2015年基本完成了所有功能模块的整理,本想等完成Camera2后再来完善接口调用,随后由于工作原因一直搁置,一放就是两年。最近突然想起,把项目拿出来修复了一些bug,完善了接口并封装成容易调用的库,Camera2暂且搁置。 10 | 11 | ### 项目结构 12 | ------ 13 | 项目包含以下两个Module: 14 | 15 | app:这个Module是一个demo,参照DemoActivity可以实现快速开发。 16 | 17 | zxing:这个Module就是Zxing Support库的源码。 18 | 19 | ### 快速入门 20 | ------ 21 | 第一步:初始化 22 | 23 | ```Java 24 | DecodeRequest request = new DecodeRequest();//需要判断的类型,此处选择默认类型 25 | zxing = new ZxingSupport(this, request); 26 | zxing.setViewfinderView((ViewfinderView) findViewById(R.id.preview_view));//设置预览 27 | zxing.setTorch((ToggleButton) findViewById(R.id.torch));//设置闪光灯,可选 28 | ``` 29 | 第二步:处理生命周期 30 | 31 | ```Java 32 | @Override 33 | protected void onResume() { 34 | super.onResume(); 35 | zxing.onResume(); 36 | if (!zxing.isOpen()) {//相机在onResume启动,此处需要判断启动是否失败 37 | new OnFailDialog(this).show(); 38 | } 39 | } 40 | 41 | @Override 42 | protected void onPause() { 43 | super.onPause(); 44 | zxing.onPause(); 45 | } 46 | 47 | @Override 48 | protected void onDestroy() { 49 | super.onDestroy(); 50 | zxing.onDestroy(); 51 | } 52 | ``` 53 | 54 | 第三步:处理回调 55 | 56 | ```Java 57 | @Override 58 | public void onScanReady() {//初始化完成 59 | zxing.requestScan();//开始扫描 60 | } 61 | 62 | @Override 63 | public void onScanSuccess(ScanResult result) {//扫描完成 64 | String scanResult = result.getRawText();//扫描所得原生数据 65 | } 66 | ``` 67 | 68 | 可选: 69 | 70 | ```Java 71 | BeepManager beep;// 播放哔声 72 | InactivityTimer timer;// 自动关闭 73 | 74 | // 自定义扫描的覆盖层 75 | Drawable draw = new ViewfinderView.FrameDrawable(){...}; //FrameDrawable支持定制边框 76 | viewfinderView.setForeground(draw); 77 | ``` 78 | ### License 79 | 80 | Copyright 2017 Yeamy. 81 | 82 | Licensed under the Apache License, Version 2.0 (the "License"); 83 | you may not use this file except in compliance with the License. 84 | You may obtain a copy of the License at 85 | 86 | http://www.apache.org/licenses/LICENSE-2.0 87 | 88 | Unless required by applicable law or agreed to in writing, software 89 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 90 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 91 | License for the specific language governing permissions and limitations under 92 | the License. -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/decode/DecodeConfig.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.decode; 2 | 3 | import com.google.zxing.BarcodeFormat; 4 | import com.google.zxing.DecodeHintType; 5 | import com.google.zxing.ResultPointCallback; 6 | 7 | import java.util.Collection; 8 | import java.util.EnumMap; 9 | import java.util.EnumSet; 10 | import java.util.Map; 11 | 12 | import static com.google.zxing.BarcodeFormat.CODABAR; 13 | import static com.google.zxing.BarcodeFormat.CODE_128; 14 | import static com.google.zxing.BarcodeFormat.CODE_39; 15 | import static com.google.zxing.BarcodeFormat.CODE_93; 16 | import static com.google.zxing.BarcodeFormat.EAN_13; 17 | import static com.google.zxing.BarcodeFormat.EAN_8; 18 | import static com.google.zxing.BarcodeFormat.ITF; 19 | import static com.google.zxing.BarcodeFormat.QR_CODE; 20 | import static com.google.zxing.BarcodeFormat.RSS_14; 21 | import static com.google.zxing.BarcodeFormat.RSS_EXPANDED; 22 | import static com.google.zxing.BarcodeFormat.UPC_A; 23 | import static com.google.zxing.BarcodeFormat.UPC_E; 24 | 25 | public class DecodeConfig { 26 | 27 | public static DecodeConfig defaultConfig() { 28 | DecodeConfig config = new DecodeConfig(); 29 | config.setDecodeFormats(DEFAULT_DECODE_FORMATS); 30 | return config; 31 | } 32 | 33 | public static final EnumSet DEFAULT_DECODE_FORMATS = EnumSet.of(// 34 | UPC_A, UPC_E, EAN_13, EAN_8, RSS_14, RSS_EXPANDED, // PRODUCT_FORMATS 35 | CODE_39, CODE_93, CODE_128, ITF, CODABAR, // INDUSTRIAL_FORMATS 36 | QR_CODE); 37 | 38 | private final Map hints = new EnumMap<>(DecodeHintType.class); 39 | private Collection decodeFormats = EnumSet.noneOf(BarcodeFormat.class); 40 | 41 | // public void putBaseHints(Map baseHints) { 42 | // if (baseHints != null) { 43 | // hints.putAll(baseHints); 44 | // } 45 | // } 46 | 47 | public void setDecodeFormats(Collection decodeFormats) { 48 | this.decodeFormats = decodeFormats; 49 | } 50 | 51 | public void addDecodeFormat(BarcodeFormat format) { 52 | decodeFormats.add(format); 53 | } 54 | 55 | public void setCharacterSet(String characterSet) { 56 | if (characterSet != null) { 57 | hints.put(DecodeHintType.CHARACTER_SET, characterSet); 58 | } 59 | } 60 | 61 | void setCallback(ResultPointCallback resultPointCallback) { 62 | hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback); 63 | } 64 | 65 | Map build() { 66 | hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); 67 | return hints; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /app/src/main/java/com/yeamy/support/zxing/demo/DemoActivity.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.demo; 2 | 3 | import android.app.Activity; 4 | import android.app.Dialog; 5 | import android.content.DialogInterface; 6 | import android.os.Bundle; 7 | import android.widget.Toast; 8 | import android.widget.ToggleButton; 9 | 10 | import com.yeamy.support.zxing.ScanResult; 11 | import com.yeamy.support.zxing.ZxingSupport; 12 | import com.yeamy.support.zxing.decode.DecodeRequest; 13 | import com.yeamy.support.zxing.plugin.BeepManager; 14 | import com.yeamy.support.zxing.plugin.InactivityTimer; 15 | import com.yeamy.support.zxing.plugin.ViewfinderView; 16 | 17 | public class DemoActivity extends Activity implements ZxingSupport.Listener { 18 | //request 19 | private ZxingSupport zxing; 20 | //option 21 | private BeepManager beep;// beep when scan result 22 | private InactivityTimer timer;//auto close activity after 15-minutes 23 | 24 | public void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | setContentView(R.layout.demo); 27 | 28 | DecodeRequest request = new DecodeRequest();//需要判断的类型,此处选择默认类型 29 | zxing = new ZxingSupport(this, request); 30 | zxing.setViewfinderView((ViewfinderView) findViewById(R.id.preview_view));//设置预览 31 | zxing.setTorch((ToggleButton) findViewById(R.id.torch));//设置闪光灯 32 | 33 | beep = new BeepManager(R.raw.beep); 34 | timer = new InactivityTimer(); 35 | } 36 | 37 | @Override 38 | protected void onResume() { 39 | super.onResume(); 40 | timer.onResume(this, InactivityTimer.INACTIVITY_DELAY_MS); 41 | beep.onResume(this); 42 | zxing.onResume(); 43 | 44 | if (!zxing.isOpen()) {//处理启动失败 45 | new OnFailDialog(this).show(); 46 | } 47 | } 48 | 49 | @Override 50 | protected void onPause() { 51 | super.onPause(); 52 | timer.onPause(); 53 | beep.onPause(); 54 | zxing.onPause(); 55 | } 56 | 57 | @Override 58 | protected void onDestroy() { 59 | super.onDestroy(); 60 | beep.close(); 61 | zxing.onDestroy(); 62 | } 63 | 64 | @Override 65 | public void onScanReady() { 66 | zxing.requestScan(); 67 | } 68 | 69 | @Override 70 | public void onScanSuccess(ScanResult result) { 71 | beep.play(); 72 | Dialog dialog = new ScanResultDialog(this, result.getRawText()).show(); 73 | dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { 74 | 75 | @Override 76 | public void onDismiss(DialogInterface dialog) { 77 | zxing.requestScan(); 78 | } 79 | });//再次扫描 80 | System.out.println(result.getRawText()); 81 | // TODO Auto-generated method stub 82 | Toast.makeText(this, result.getRawText(), Toast.LENGTH_SHORT).show(); 83 | } 84 | 85 | } -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/camera/AutoFocusManager.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.camera; 2 | 3 | import android.hardware.Camera; 4 | import android.util.Log; 5 | 6 | import com.yeamy.support.zxing.LooperThread; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collection; 10 | 11 | /** 12 | * Code come from zxing-android with little modification, can be replay by the original file; 13 | */ 14 | @SuppressWarnings("deprecation") 15 | public final class AutoFocusManager implements Camera.AutoFocusCallback, Runnable { 16 | 17 | private static final String TAG = AutoFocusManager.class.getSimpleName(); 18 | 19 | private static final long AUTO_FOCUS_INTERVAL_MS = 2000L; 20 | private static final Collection FOCUS_MODES_CALLING_AF; 21 | 22 | static { 23 | FOCUS_MODES_CALLING_AF = new ArrayList<>(2); 24 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO); 25 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO); 26 | } 27 | 28 | private boolean stopped = true; 29 | private boolean focusing = false; 30 | private boolean useAutoFocus; 31 | private Camera camera; 32 | private LooperThread thread; 33 | 34 | public AutoFocusManager(LooperThread thread) { 35 | this.thread = thread; 36 | } 37 | 38 | void init(Camera camera) { 39 | this.camera = camera; 40 | String currentFocusMode = camera.getParameters().getFocusMode(); 41 | useAutoFocus = FOCUS_MODES_CALLING_AF.contains(currentFocusMode); 42 | Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus); 43 | } 44 | 45 | @Override 46 | public synchronized void onAutoFocus(boolean success, Camera theCamera) { 47 | focusing = false; 48 | autoFocusAgainLater(); 49 | } 50 | 51 | private synchronized void autoFocusAgainLater() { 52 | if (!stopped) { 53 | thread.postDelayed(this, AUTO_FOCUS_INTERVAL_MS); 54 | } 55 | } 56 | 57 | public synchronized void start() { 58 | stopped = false; 59 | run(); 60 | } 61 | 62 | public synchronized void stop() { 63 | stopped = true; 64 | if (useAutoFocus) { 65 | thread.removeCallbacks(this); 66 | // Doesn't hurt to call this even if not focusing 67 | try { 68 | camera.cancelAutoFocus(); 69 | } catch (RuntimeException re) { 70 | // Have heard RuntimeException reported in Android 4.0.x+; continue? 71 | Log.w(TAG, "Unexpected exception while cancelling focusing", re); 72 | } 73 | } 74 | } 75 | 76 | @Override 77 | public synchronized void run() { 78 | if (useAutoFocus && !stopped && !focusing) { 79 | try { 80 | camera.autoFocus(this); 81 | focusing = true; 82 | } catch (RuntimeException re) { 83 | // Have heard RuntimeException reported in Android 4.0.x+; continue? 84 | Log.w(TAG, "Unexpected exception while focusing", re); 85 | // Try again later to keep cycle going 86 | autoFocusAgainLater(); 87 | } 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/decode/DecodeRequest.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.decode; 2 | 3 | import com.google.zxing.BinaryBitmap; 4 | import com.google.zxing.MultiFormatReader; 5 | import com.google.zxing.PlanarYUVLuminanceSource; 6 | import com.google.zxing.ReaderException; 7 | import com.google.zxing.Result; 8 | import com.google.zxing.ResultPoint; 9 | import com.google.zxing.ResultPointCallback; 10 | import com.google.zxing.common.HybridBinarizer; 11 | import com.yeamy.support.zxing.ScanResult; 12 | 13 | public class DecodeRequest implements Runnable, ResultPointCallback { 14 | private final MultiFormatReader multiFormatReader; 15 | private ResultPointCallback pointCallback; 16 | private DecodeCallback callback; 17 | private DecodeBean bean; 18 | 19 | /** 20 | * width Default Config 21 | */ 22 | public DecodeRequest() { 23 | this(DecodeConfig.defaultConfig()); 24 | } 25 | 26 | public DecodeRequest(DecodeConfig config) { 27 | this.multiFormatReader = new MultiFormatReader(); 28 | config.setCallback(this); 29 | multiFormatReader.setHints(config.build()); 30 | } 31 | 32 | public void setRequest(DecodeBean bean, DecodeCallback callback, ResultPointCallback pointCallback) { 33 | this.bean = bean; 34 | this.callback = callback; 35 | this.pointCallback = pointCallback; 36 | } 37 | 38 | @Override 39 | public void run() { 40 | ScanResult result = decode(bean); 41 | if (result != null) { 42 | callback.onDecodeSuccess(result); 43 | } else { 44 | callback.onDecodeFail(); 45 | } 46 | } 47 | 48 | private ScanResult decode(DecodeBean bean) { 49 | Result rawResult = null; 50 | // long start = System.currentTimeMillis(); 51 | // System.out.println("dataWidth = " + bean.dataWidth + // 52 | // " dataHeight = " + bean.dataHeight + // 53 | // " left = " + bean.left + // 54 | // " top = " + bean.top + // 55 | // " width = " + bean.width + // 56 | // " height = " + bean.height + // 57 | // " reverseHorizontal = " + bean.reverseHorizontal); 58 | PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(bean.yuvData, bean.dataWidth, bean.dataHeight, 59 | bean.left, bean.top, bean.width, bean.height, false); 60 | BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 61 | try { 62 | rawResult = multiFormatReader.decodeWithState(bitmap); 63 | } catch (ReaderException re) { 64 | // continue 65 | } finally { 66 | bean.reset(); 67 | multiFormatReader.reset(); 68 | } 69 | // long end = System.currentTimeMillis(); 70 | // System.out.println("Found barcode in " + (end - start) + " ms"); 71 | if (rawResult != null) { 72 | return new ScanResult(rawResult); 73 | } 74 | return null; 75 | } 76 | 77 | @Override 78 | public void foundPossibleResultPoint(ResultPoint point) { 79 | if (pointCallback != null) { 80 | pointCallback.foundPossibleResultPoint(point); 81 | } 82 | } 83 | 84 | public interface DecodeCallback { 85 | 86 | void onDecodeSuccess(ScanResult result); 87 | 88 | void onDecodeFail(); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/camera/CameraImpl.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.camera; 2 | 3 | import android.hardware.Camera; 4 | import android.hardware.Camera.Parameters; 5 | import android.view.TextureView; 6 | 7 | import com.yeamy.support.zxing.CameraShotListener; 8 | import com.yeamy.support.zxing.Viewfinder; 9 | 10 | import java.util.List; 11 | 12 | import static android.hardware.Camera.Parameters.FLASH_MODE_OFF; 13 | import static android.hardware.Camera.Parameters.FLASH_MODE_TORCH; 14 | 15 | @SuppressWarnings("deprecation") 16 | public final class CameraImpl { 17 | 18 | private Camera device; 19 | 20 | private PreviewManager previewManager = new PreviewManager(); 21 | private AutoFocusManager autoFocus; 22 | private boolean af; 23 | 24 | public PreviewManager getPreviewManager() { 25 | return previewManager; 26 | } 27 | 28 | public void setCameraShotListener(final CameraShotListener l) { 29 | device.setOneShotPreviewCallback(new Camera.PreviewCallback() { 30 | @Override 31 | public void onPreviewFrame(byte[] data, Camera camera) { 32 | l.onCameraShot(data); 33 | } 34 | }); 35 | } 36 | 37 | public boolean open() { 38 | return open(-1); 39 | } 40 | 41 | public boolean open(int cameraId) { 42 | Camera camera; 43 | if (cameraId >= 0) { 44 | camera = Camera.open(cameraId); 45 | } else { 46 | camera = Camera.open(); 47 | } 48 | this.device = camera; 49 | return camera != null; 50 | } 51 | 52 | public boolean isOpen() { 53 | return this.device != null; 54 | } 55 | 56 | public void setAutoFocus(AutoFocusManager afm) { 57 | this.autoFocus = afm; 58 | afm.init(this.device); 59 | } 60 | 61 | private boolean isAutoFocusRunning() { 62 | return previewManager.isPreviewing() && af && autoFocus != null; 63 | } 64 | 65 | public void startAutoFocus() { 66 | af = true; 67 | if (previewManager.isPreviewing() && autoFocus != null) { 68 | autoFocus.start(); 69 | } 70 | } 71 | 72 | public void stopAutoFocus() { 73 | af = false; 74 | if (autoFocus != null) { 75 | autoFocus.stop(); 76 | } 77 | } 78 | 79 | public boolean supportTorch() { 80 | Parameters params = device.getParameters(); 81 | List modes = params.getSupportedFlashModes(); 82 | return modes != null && modes.contains(FLASH_MODE_TORCH); 83 | } 84 | 85 | public void setTorch(boolean on) { 86 | boolean af = isAutoFocusRunning(); 87 | if (af) { 88 | stopAutoFocus(); 89 | } 90 | Parameters params = device.getParameters(); 91 | params.setFlashMode(on ? FLASH_MODE_TORCH : FLASH_MODE_OFF); 92 | device.setParameters(params); 93 | if (af) { 94 | startAutoFocus(); 95 | } 96 | } 97 | 98 | public void close() { 99 | if (device != null) { 100 | stopAutoFocus(); 101 | previewManager.stopPreview(); 102 | device.release(); 103 | device = null; 104 | } 105 | } 106 | 107 | public void requestPreview(TextureView pv, Viewfinder vf) { 108 | previewManager.requestPreview(device, pv, vf); 109 | } 110 | 111 | } -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/ZxingSupport.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing; 2 | 3 | import android.widget.CompoundButton; 4 | 5 | import com.yeamy.support.zxing.camera.AutoFocusManager; 6 | import com.yeamy.support.zxing.camera.CameraImpl; 7 | import com.yeamy.support.zxing.camera.ScanManager; 8 | import com.yeamy.support.zxing.decode.DecodeRequest; 9 | import com.yeamy.support.zxing.plugin.ViewfinderView; 10 | 11 | public class ZxingSupport { 12 | //request 13 | private LooperThread thread; 14 | private CameraImpl camera; 15 | private ScanManager scan; 16 | private Listener l; 17 | 18 | private ViewfinderView viewfinderView; 19 | private CompoundButton torch; 20 | 21 | public ZxingSupport(Listener l, DecodeRequest decode) { 22 | //init thread 23 | LooperThread thread = new LooperThread(); 24 | thread.start(); 25 | //init camera 26 | CameraImpl camera = new CameraImpl(); 27 | //init scan & decode 28 | scan = new ScanManager(thread, camera, l, decode); 29 | //init view & vf 30 | this.thread = thread; 31 | this.camera = camera; 32 | this.l = l; 33 | } 34 | 35 | public void setViewfinderView(ViewfinderView viewfinderView) { 36 | this.viewfinderView = viewfinderView; 37 | startPreview(); 38 | } 39 | 40 | private void startPreview() { 41 | CameraImpl camera = this.camera; 42 | ViewfinderView view = this.viewfinderView; 43 | if (camera != null && camera.isOpen() && view != null) { 44 | viewfinderView.setPreviewListener(callback); 45 | camera.requestPreview(view.getTextureView(), view); 46 | } 47 | } 48 | 49 | private Callback callback = new Callback(); 50 | 51 | private class Callback implements ViewfinderView.PreviewListener, 52 | CompoundButton.OnCheckedChangeListener { 53 | 54 | @Override 55 | public void onViewCreated() { 56 | startPreview(); 57 | } 58 | 59 | @Override 60 | public void onPreviewStart() { 61 | l.onScanReady(); 62 | } 63 | 64 | @Override 65 | public void onCheckedChanged(CompoundButton torch, boolean isChecked) { 66 | camera.setTorch(isChecked); 67 | } 68 | } 69 | 70 | public void setTorch(CompoundButton torch) { 71 | this.torch = torch; 72 | initTorch(); 73 | } 74 | 75 | private void initTorch() { 76 | if (camera.isOpen() && torch != null) { 77 | //init torch 78 | if (camera.supportTorch()) { 79 | torch.setOnCheckedChangeListener(callback); 80 | if (torch.isChecked()) camera.setTorch(true); 81 | } else { 82 | torch.setEnabled(false); 83 | } 84 | } 85 | } 86 | 87 | public void onResume() { 88 | if (camera.open()) { 89 | camera.setAutoFocus(new AutoFocusManager(thread)); 90 | startPreview(); 91 | } 92 | initTorch(); 93 | } 94 | 95 | public boolean isOpen() { 96 | return camera.isOpen(); 97 | } 98 | 99 | public void onPause() { 100 | camera.close(); 101 | } 102 | 103 | public void onDestroy() { 104 | thread.close(); 105 | } 106 | 107 | public void requestScan() { 108 | scan.requestScan(); 109 | } 110 | 111 | public interface Listener extends ScanResultListener { 112 | /** 113 | * 初始化完成 114 | */ 115 | void onScanReady(); 116 | } 117 | } -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/camera/ScanManager.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.camera; 2 | 3 | import android.graphics.Rect; 4 | 5 | import com.yeamy.support.zxing.CameraShotListener; 6 | import com.yeamy.support.zxing.LooperThread; 7 | import com.yeamy.support.zxing.ScanResult; 8 | import com.yeamy.support.zxing.ScanResultListener; 9 | import com.yeamy.support.zxing.Size; 10 | import com.yeamy.support.zxing.Viewfinder; 11 | import com.yeamy.support.zxing.decode.DecodeBean; 12 | import com.yeamy.support.zxing.decode.DecodeRequest; 13 | import com.yeamy.support.zxing.decode.DecodeRequest.DecodeCallback; 14 | 15 | public class ScanManager implements CameraShotListener, DecodeCallback { 16 | private final DecodeBean bean; 17 | private final DecodeRequest decode; 18 | private ScanResultListener listener; 19 | private CameraImpl camera; 20 | private LooperThread thread; 21 | private boolean ready = true; 22 | 23 | public ScanManager(LooperThread thread, CameraImpl camera, ScanResultListener listener, 24 | DecodeRequest decode) { 25 | this.thread = thread; 26 | this.camera = camera; 27 | this.listener = listener; 28 | this.decode = decode; 29 | this.bean = new DecodeBean(); 30 | } 31 | 32 | public boolean requestScan() { 33 | PreviewManager pm = camera.getPreviewManager(); 34 | if (pm.isPreviewing() && ready) { 35 | camera.startAutoFocus(); 36 | startScan(); 37 | ready = false; 38 | return true; 39 | } 40 | return false; 41 | } 42 | 43 | private void startScan() { 44 | if (camera.isOpen()) { 45 | camera.setCameraShotListener(this); 46 | } 47 | } 48 | 49 | @Override 50 | public final void onCameraShot(byte[] data) { 51 | // Size s = camera.getParameters().getPreviewSize(); 52 | // System.out.println("!!!==============> " + s.width + " " + s.height); 53 | PreviewManager pm = this.camera.getPreviewManager(); 54 | Size size = pm.getPreviewSize(); 55 | int dataWidth = size.width; 56 | int dataHeight = size.height; 57 | bean.setSource(data, dataWidth, dataHeight); 58 | // frame 59 | int left, top, vw, vh, width, height; 60 | Viewfinder viewfinder = pm.getViewfinder(); 61 | Size view = viewfinder.getPreviewSize(); 62 | vw = view.width; 63 | vh = view.height; 64 | Rect frame = viewfinder.getFrameRect(); 65 | 66 | boolean portrait = viewfinder.getOrientation() % 180 != 0; 67 | if (portrait) {// portrait 68 | left = frame.top * dataWidth / vh; 69 | top = (vw - frame.right) * dataWidth / vh; 70 | width = frame.height() * dataWidth / vh; 71 | height = frame.width() * dataWidth / vh; 72 | bean.setFrameRectPortrait(left, top, width, height); 73 | } else {// landspace 74 | left = frame.left * dataWidth / vw; 75 | top = frame.top * dataWidth / vw; 76 | width = frame.width() * dataWidth / vw; 77 | height = frame.height() * dataWidth / vw; 78 | bean.setFrameRectLandspace(left, top, width, height); 79 | } 80 | // done 81 | decode.setRequest(bean, this, viewfinder);// jump to decode 82 | thread.post(decode); 83 | } 84 | 85 | @Override 86 | public final void onDecodeSuccess(ScanResult result) { 87 | listener.onScanSuccess(result); 88 | camera.stopAutoFocus(); 89 | bean.clearBuff(); 90 | ready = true; 91 | } 92 | 93 | @Override 94 | public void onDecodeFail() { 95 | startScan(); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/decode/DecodeBean.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.decode; 2 | 3 | public class DecodeBean { 4 | 5 | public byte[] yuvData; 6 | public int dataWidth; 7 | public int dataHeight; 8 | public int left; 9 | public int top; 10 | public int width; 11 | public int height; 12 | private byte[] cropBuff; 13 | // public boolean portrait = false; 14 | 15 | public void setSource(byte[] yuvData, int dataWidth, int dataHeight) { 16 | this.yuvData = yuvData; 17 | this.dataWidth = dataWidth; 18 | this.dataHeight = dataHeight; 19 | } 20 | 21 | public void setFrameRectLandspace(int left, int top, int width, int height) { 22 | // landspace no need to do anything, due to the zxing framework will do it 23 | this.left = left; 24 | this.top = top; 25 | this.width = width; 26 | this.height = height; 27 | } 28 | 29 | public void setFrameRectPortrait(int left, int top, int width, int height) { 30 | if (cropBuff == null) { 31 | cropBuff = new byte[width * height * 3 / 2]; 32 | } 33 | YV12CropAndRotate90(yuvData, dataWidth, dataHeight, // 34 | cropBuff, top, left, width, height); 35 | this.left = 0; 36 | this.top = 0; 37 | this.width = this.dataWidth = height; 38 | this.height = this.dataHeight = width; 39 | yuvData = cropBuff; 40 | } 41 | 42 | void reset() { 43 | yuvData = null; 44 | } 45 | 46 | /** 47 | * call when stop scan 48 | */ 49 | public void clearBuff() { 50 | cropBuff = null; 51 | cropBuff = null; 52 | } 53 | 54 | /** 55 | * @param dst length must equle [width * height * 3 / 2] 56 | * @param top The top of {@code src} as the start of {@code dst} 57 | * @param left The left of {@code src} as the start of {@code dst} 58 | * @param width The width of {@code dst} before rotate 59 | * @param height The height of {@code dst} before rotate 60 | */ 61 | public static void YV12CropAndRotate90(byte[] src, int srcWidth, int srcHeight, // 62 | byte[] dst, int top, int left, int width, int height) { 63 | int c_top = top / 2; 64 | int c_left = left / 2; 65 | int i = 0; 66 | 67 | int cr_offset = srcWidth * srcHeight; 68 | int c_width = width / 2; 69 | int c_height = height / 2; 70 | int src_c_width = srcWidth / 2; 71 | int src_c_size = src_c_width * srcHeight / 2; 72 | int cb_offset = cr_offset + src_c_size; 73 | 74 | for (int x = 0; x < width; x++) { 75 | for (int y = height - 1; y >= 0; y--) { 76 | dst[i++] = src[srcWidth * (top + y) + left + x]; 77 | } 78 | } 79 | for (int x = 0; x < c_width; x++) { 80 | for (int y = c_height - 1; y >= 0; y--) { 81 | dst[i++] = src[cr_offset + src_c_width * (c_top + y) + c_left + x]; 82 | } 83 | } 84 | for (int x = 0; x < c_width; x++) { 85 | for (int y = c_height - 1; y >= 0; y--) { 86 | dst[i++] = src[cb_offset + src_c_width * (c_top + y) + c_left + x]; 87 | } 88 | } 89 | } 90 | 91 | // public static void YV12Rotate90(byte[] src, byte[] dst, int srcWidth, int srcHeight) { 92 | // int y_size = srcWidth * srcHeight; 93 | // int cr_offset = y_size; 94 | // int c_width = srcWidth / 2; 95 | // int c_height = srcHeight / 2; 96 | // int c_size = c_width * c_height; 97 | // int cb_offset = cr_offset + c_size; 98 | // 99 | // int i = 0; 100 | // for (int x = 0; x < srcWidth; x++) { 101 | // for (int y = srcHeight - 1; y >= 0; y--) { 102 | // dst[i++] = src[srcWidth * y + x]; 103 | // } 104 | // } 105 | // for (int x = 0; x < c_width; x++) { 106 | // for (int y = c_height - 1; y >= 0; y--) { 107 | // dst[i++] = src[cr_offset + c_width * y + x]; 108 | // } 109 | // } 110 | // for (int x = 0; x < c_width; x++) { 111 | // for (int y = c_height - 1; y >= 0; y--) { 112 | // dst[i++] = src[cb_offset + c_width * y + x]; 113 | // } 114 | // } 115 | // } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/camera/PreviewManager.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.camera; 2 | 3 | import android.graphics.SurfaceTexture; 4 | import android.hardware.Camera; 5 | import android.hardware.Camera.Parameters; 6 | import android.view.TextureView; 7 | 8 | import com.yeamy.support.zxing.Viewfinder; 9 | import com.yeamy.support.zxing.Size; 10 | 11 | import java.util.List; 12 | 13 | import static com.yeamy.support.zxing.Viewfinder.MIN_PREVIEW_PIXELS; 14 | 15 | @SuppressWarnings("deprecation") 16 | public final class PreviewManager { 17 | 18 | private Camera device; 19 | private Viewfinder viewfinder; 20 | private Size previewSize; 21 | private TextureView previewView; 22 | 23 | public Size getPreviewSize() { 24 | return previewSize; 25 | } 26 | 27 | public Viewfinder getViewfinder() { 28 | return viewfinder; 29 | } 30 | 31 | public boolean isPreviewing() { 32 | return viewfinder != null; 33 | } 34 | 35 | public void requestPreview(Camera device, TextureView pv, Viewfinder vf) { 36 | this.device = device; 37 | this.viewfinder = vf; 38 | this.previewView = pv; 39 | setPreviewSize(vf); 40 | Listener l = new Listener(); 41 | if (pv.isAvailable()) { 42 | l.onSurfaceTextureAvailable(pv.getSurfaceTexture(), 0, 0); 43 | } 44 | pv.setSurfaceTextureListener(l); 45 | device.setDisplayOrientation(vf.getOrientation()); 46 | } 47 | 48 | private void setPreviewSize(Viewfinder vf) { 49 | Parameters params = device.getParameters(); 50 | List list = params.getSupportedPreviewSizes(); 51 | if (list == null || list.size() == 0) { 52 | return; 53 | } 54 | // ---------- plan 55 | Size plan = vf.getPreviewSize(); 56 | //default is land 57 | if (vf.getOrientation() % 180 != 0) { 58 | plan.rotate(); 59 | } 60 | int planWidth = plan.width; 61 | int planHeight = plan.height; 62 | int planPix = planWidth * planHeight; 63 | // ---------- default 64 | android.hardware.Camera.Size defaultSize = params.getPreviewSize(); 65 | // ----------- find best 66 | int maxPx = defaultSize.width * defaultSize.height; 67 | android.hardware.Camera.Size maxSize = defaultSize; 68 | for (android.hardware.Camera.Size size : list) { 69 | int width = size.width, height = size.height; 70 | if (width > planWidth || height > planHeight) { 71 | continue; 72 | } 73 | int px = width * height; 74 | if (planPix >= px && px >= MIN_PREVIEW_PIXELS && px > maxPx) { 75 | maxSize = size; 76 | maxPx = px; 77 | } 78 | } 79 | if (!maxSize.equals(defaultSize)) { 80 | params.setPreviewSize(maxSize.width, maxSize.height); 81 | device.setParameters(params); 82 | } 83 | previewSize = new Size(maxSize.width, maxSize.height); 84 | } 85 | 86 | private void startPreview(SurfaceTexture surface, Viewfinder vf) { 87 | viewfinder = vf; 88 | try { 89 | device.setPreviewTexture(surface); 90 | device.startPreview(); 91 | } catch (Exception e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | 96 | public void stopPreview() { 97 | device.stopPreview(); 98 | if (previewView != null) { 99 | previewView.setSurfaceTextureListener(null); 100 | previewView = null; 101 | } 102 | viewfinder = null; 103 | } 104 | 105 | private class Listener implements TextureView.SurfaceTextureListener { 106 | 107 | public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { 108 | Viewfinder vf = viewfinder; 109 | startPreview(surface, vf); 110 | if (vf.getOrientation() % 180 == 0) { 111 | vf.onStartPreview(previewView, previewSize.width, previewSize.height); 112 | } else { 113 | vf.onStartPreview(previewView, previewSize.height, previewSize.width); 114 | } 115 | } 116 | 117 | public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { 118 | // Ignored, Camera does all the work for us 119 | } 120 | 121 | public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { 122 | stopPreview(); 123 | return true; 124 | } 125 | 126 | public void onSurfaceTextureUpdated(SurfaceTexture surface) { 127 | // Invoked every time there's a new Camera preview frame 128 | } 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /zxing/src/main/java/com/yeamy/support/zxing/plugin/ViewfinderView.java: -------------------------------------------------------------------------------- 1 | package com.yeamy.support.zxing.plugin; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Canvas; 6 | import android.graphics.ColorFilter; 7 | import android.graphics.Paint; 8 | import android.graphics.PixelFormat; 9 | import android.graphics.Rect; 10 | import android.graphics.drawable.Drawable; 11 | import android.util.AttributeSet; 12 | import android.view.Gravity; 13 | import android.view.TextureView; 14 | import android.widget.FrameLayout; 15 | 16 | import com.google.zxing.ResultPoint; 17 | import com.yeamy.support.zxing.R; 18 | import com.yeamy.support.zxing.Size; 19 | import com.yeamy.support.zxing.Viewfinder; 20 | 21 | import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; 22 | 23 | /** 24 | * The best way to instance Viewfinder is to create a view implements it
25 | * invoke {@link #setForeground(Drawable)} to change cover frame 26 | */ 27 | public class ViewfinderView extends FrameLayout implements Viewfinder { 28 | private int frameTop, frameLeft, frameRight, frameBottom; 29 | private Size viewRect; 30 | private Rect frameRect; 31 | private boolean created; 32 | protected TextureView textureView; 33 | protected LayoutParams textureParams; 34 | private PreviewListener listener; 35 | 36 | public ViewfinderView(Context context, AttributeSet attrs) { 37 | this(context, attrs, 0); 38 | } 39 | 40 | public ViewfinderView(Context context, AttributeSet attrs, int defStyleAttr) { 41 | super(context, attrs, defStyleAttr); 42 | final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewfinderView, 0, 0); 43 | frameTop = a.getDimensionPixelSize(R.styleable.ViewfinderView_frameTop, -1); 44 | frameLeft = a.getDimensionPixelSize(R.styleable.ViewfinderView_frameLeft, 0); 45 | frameRight = a.getDimensionPixelSize(R.styleable.ViewfinderView_frameRight, 0); 46 | frameBottom = a.getDimensionPixelSize(R.styleable.ViewfinderView_frameBottom, -1); 47 | a.recycle(); 48 | 49 | LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT); 50 | params.gravity = Gravity.CENTER_HORIZONTAL; 51 | TextureView view = new TextureView(context); 52 | addView(view, 0, params); 53 | this.textureView = view; 54 | this.textureParams = params; 55 | this.viewRect = new Size(0,0); 56 | this.frameRect = new Rect(); 57 | 58 | setForeground(new SimpleFrameDrawable()); 59 | } 60 | 61 | @Override 62 | public void setForeground(Drawable drawable) { 63 | if (drawable != null && drawable instanceof FrameDrawable) { 64 | FrameDrawable draw = (FrameDrawable) drawable; 65 | draw.setFrameRect(frameRect); 66 | } 67 | super.setForeground(drawable); 68 | } 69 | 70 | /** 71 | * @return the real display view 72 | */ 73 | public TextureView getTextureView() { 74 | return textureView; 75 | } 76 | 77 | public void setPreviewListener(PreviewListener listener) { 78 | this.listener = listener; 79 | if (created) { 80 | listener.onViewCreated(); 81 | } 82 | } 83 | 84 | /** 85 | * get the size of this view at the first time here 86 | */ 87 | @Override 88 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 89 | super.onLayout(changed, left, top, right, bottom); 90 | if (changed) { 91 | reSizeRect(left, top, right, bottom); 92 | if (listener != null) { 93 | listener.onViewCreated(); 94 | } 95 | created = true; 96 | } 97 | } 98 | 99 | private void reSizeRect(int left, int top, int right, int bottom) { 100 | viewRect.width = right - left; 101 | viewRect.height = bottom - top; 102 | 103 | frameRect.left = left + frameLeft; 104 | frameRect.right = right - frameRight; 105 | if (frameTop == -1) { 106 | if (frameBottom == -1) { 107 | frameRect.top = top; 108 | frameRect.bottom = frameRect.top + frameRect.width(); 109 | } else { 110 | frameRect.bottom = bottom - frameBottom; 111 | frameRect.top = frameRect.bottom - frameRect.width(); 112 | } 113 | } else { 114 | if (frameBottom == -1) { 115 | frameRect.top = top + frameTop; 116 | frameRect.bottom = frameRect.top + frameRect.width(); 117 | } else { 118 | frameRect.top = top + frameTop; 119 | frameRect.bottom = bottom - frameBottom; 120 | } 121 | } 122 | if (frameRect.top < 0) { 123 | frameRect.top = 0; 124 | } 125 | if (frameRect.bottom > bottom) { 126 | frameRect.bottom = bottom; 127 | } 128 | } 129 | 130 | @Override 131 | public void foundPossibleResultPoint(ResultPoint point) { 132 | } 133 | 134 | @Override 135 | public Size getPreviewSize() { 136 | return viewRect; 137 | } 138 | 139 | @Override 140 | public Rect getFrameRect() { 141 | return frameRect; 142 | } 143 | 144 | @Override 145 | public int getOrientation() { 146 | return 90; 147 | } 148 | 149 | /** 150 | * resize the preview-View 151 | */ 152 | @Override 153 | public void onStartPreview(TextureView view, int pw, int ph) { 154 | // resize 155 | int width = getWidth(); 156 | int height = getHeight(); 157 | int surfaceWidth, surfaceHeight; 158 | if (width * ph > height * pw) {// 16:9 159 | surfaceWidth = pw * height / ph; 160 | surfaceHeight = height; 161 | } else {// 4:3 162 | surfaceWidth = width; 163 | surfaceHeight = ph * width / pw; 164 | } 165 | LayoutParams params = textureParams; 166 | params.width = surfaceWidth; 167 | params.height = surfaceHeight; 168 | textureView.setLayoutParams(params); 169 | 170 | int x = (width - surfaceWidth) / 2; 171 | reSizeRect(getLeft() + x, // 172 | getTop(), // 173 | getRight() - x, // 174 | getTop() + surfaceHeight); 175 | if (listener != null) { 176 | listener.onPreviewStart(); 177 | } 178 | } 179 | 180 | /** 181 | * the frame rect of viewfinder width four corner 182 | */ 183 | public static abstract class FrameDrawable extends Drawable { 184 | private Paint paint = new Paint(); 185 | private Rect frameRect; 186 | 187 | private void setFrameRect(Rect frameRect) { 188 | this.frameRect = frameRect; 189 | } 190 | 191 | public Rect getFrameRect() { 192 | return frameRect; 193 | } 194 | 195 | public Paint getPaint() { 196 | return paint; 197 | } 198 | } 199 | 200 | public static class SimpleFrameDrawable extends FrameDrawable { 201 | private int laseColor = 0x90000000; 202 | private int frameColor = 0x60ffffff; 203 | private int cornerColor = 0xc0ffffff; 204 | 205 | public void setLaseColor(int laseColor) { 206 | this.laseColor = laseColor; 207 | } 208 | 209 | public void setFrameColor(int frameColor) { 210 | this.frameColor = frameColor; 211 | } 212 | 213 | public void setCornerColor(int cornerColor) { 214 | this.cornerColor = cornerColor; 215 | } 216 | 217 | @Override 218 | public void draw(Canvas canvas) { 219 | int width = canvas.getWidth(); 220 | int height = canvas.getHeight(); 221 | Rect frameRect = getFrameRect(); 222 | int top = frameRect.top; 223 | int left = frameRect.left; 224 | int right = frameRect.right; 225 | int bottom = frameRect.bottom; 226 | Paint paint = getPaint(); 227 | // lase 228 | paint.setColor(laseColor); 229 | canvas.drawRect(0, 0, width, top, paint);// top 230 | canvas.drawRect(0, top, left, bottom, paint);// bottom 231 | canvas.drawRect(0, bottom, width, height, paint);// left 232 | canvas.drawRect(right, top, width, bottom, paint);// right 233 | // frame 234 | paint.setColor(frameColor); 235 | float[] pts = new float[]{left, top, right, top, // top 236 | left, bottom, right, bottom, // bottom 237 | left, top, left, bottom, // left 238 | right, top, right, bottom,// right; 239 | }; 240 | canvas.drawLines(pts, paint); 241 | // corners 242 | paint.setColor(cornerColor); 243 | int xlength = frameRect.width() / 20; 244 | int ylength = frameRect.height() / 20; 245 | int dm = frameRect.width() / 27; 246 | top += dm; 247 | left += dm; 248 | right -= dm; 249 | bottom -= dm; 250 | float[] corners = new float[]{ // 251 | left, top, left + xlength, top, // left-top-h 252 | left, top, left, top + ylength, // left-top-v 253 | right, top, right - xlength, top, // right-top-h 254 | right, top, right, top + ylength, // right-top-v 255 | left, bottom, left + xlength, bottom, // left-top-h 256 | left, bottom, left, bottom - ylength, // left-top-v 257 | right, bottom, right - xlength, bottom, // right-top-h 258 | right, bottom, right, bottom - ylength, // right-top-v 259 | }; 260 | canvas.drawLines(corners, paint); 261 | } 262 | 263 | @Override 264 | public void setAlpha(int alpha) { 265 | } 266 | 267 | @Override 268 | public void setColorFilter(ColorFilter cf) { 269 | } 270 | 271 | @Override 272 | public int getOpacity() { 273 | return PixelFormat.TRANSLUCENT; 274 | } 275 | 276 | } 277 | 278 | public interface PreviewListener { 279 | void onViewCreated(); 280 | 281 | void onPreviewStart(); 282 | } 283 | } 284 | --------------------------------------------------------------------------------