├── demo ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ ├── values │ │ │ ├── dimens.xml │ │ │ ├── colors.xml │ │ │ ├── styles.xml │ │ │ └── strings.xml │ │ ├── drawable │ │ │ ├── ic_flash_on.xml │ │ │ ├── ic_flash_off.xml │ │ │ ├── ic_aspect_ratio.xml │ │ │ ├── ic_flash_auto.xml │ │ │ ├── ic_switch_camera.xml │ │ │ └── ic_camera.xml │ │ ├── layout │ │ │ ├── dialog_picture.xml │ │ │ └── activity_main.xml │ │ ├── menu │ │ │ └── main.xml │ │ └── layout-land │ │ │ └── activity_main.xml │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── android │ │ │ └── cameraview │ │ │ └── demo │ │ │ ├── MainApplication.java │ │ │ ├── PictureDialogFragment.java │ │ │ ├── ConfirmationDialogFragment.java │ │ │ ├── AspectRatioFragment.java │ │ │ └── MainActivity.java │ │ └── AndroidManifest.xml └── build.gradle ├── library ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── drawable │ │ │ │ ├── focus_marker_fill.xml │ │ │ │ └── focus_marker_outline.xml │ │ │ ├── layout-v14 │ │ │ │ ├── layout_focus_marker.xml │ │ │ │ └── texture_view.xml │ │ │ ├── values │ │ │ │ ├── public.xml │ │ │ │ ├── styles.xml │ │ │ │ └── attrs.xml │ │ │ └── layout │ │ │ │ └── surface_view.xml │ │ ├── AndroidManifest.xml │ │ ├── base │ │ │ └── com │ │ │ │ └── google │ │ │ │ └── android │ │ │ │ └── cameraview │ │ │ │ ├── Constants.java │ │ │ │ ├── CameraHelper.java │ │ │ │ ├── PreviewImpl.java │ │ │ │ ├── Size.java │ │ │ │ ├── CameraViewImpl.java │ │ │ │ ├── SizeMap.java │ │ │ │ ├── FocusMarkerView.java │ │ │ │ ├── DisplayOrientationDetector.java │ │ │ │ ├── CameraLogDefaultLoggingDelegate.java │ │ │ │ ├── AspectRatio.java │ │ │ │ ├── LoggingDelegate.java │ │ │ │ └── CameraLog.java │ │ ├── api23 │ │ │ └── com │ │ │ │ └── google │ │ │ │ └── android │ │ │ │ └── cameraview │ │ │ │ └── Camera2Api23.java │ │ ├── api9 │ │ │ └── com │ │ │ │ └── google │ │ │ │ └── android │ │ │ │ └── cameraview │ │ │ │ └── SurfaceViewPreview.java │ │ └── api14 │ │ │ └── com │ │ │ └── google │ │ │ └── android │ │ │ └── cameraview │ │ │ └── TextureViewPreview.java │ ├── androidTest │ │ ├── AndroidManifest.xml │ │ ├── res │ │ │ └── layout │ │ │ │ └── activity_camera_view.xml │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── android │ │ │ └── cameraview │ │ │ ├── CameraViewActivity.java │ │ │ ├── CameraViewMatchers.java │ │ │ ├── CameraViewActions.java │ │ │ ├── AspectRatioIsCloseTo.java │ │ │ ├── AspectRatioInstrumentationTest.java │ │ │ └── CameraViewTest.java │ └── test │ │ └── java │ │ └── com │ │ └── google │ │ └── android │ │ └── cameraview │ │ ├── SizeMapTest.java │ │ ├── SizeTest.java │ │ └── AspectRatioTest.java └── build.gradle ├── cameraview_screenshot.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .idea ├── copyright │ ├── profiles_settings.xml │ └── Apache_License_2_0.xml └── codeStyleSettings.xml ├── .gitignore ├── settings.gradle ├── gradle.properties ├── CONTRIBUTING.md ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /demo/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /cameraview_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/cameraview_screenshot.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javayhu/CameraView/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | .DS_Store 5 | /build 6 | /captures 7 | 8 | .idea/ 9 | !.idea/copyright/*.xml 10 | !.idea/codeStyleSettings.xml 11 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/focus_marker_fill.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Sep 06 09:02:59 JST 2016 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-3.3-all.zip 7 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/focus_marker_outline.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016 The Android Open Source Project 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | include ':demo', ':library' 16 | -------------------------------------------------------------------------------- /demo/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 64dp 16 | 17 | -------------------------------------------------------------------------------- /.idea/copyright/Apache_License_2_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16dp 16 | 16dp 17 | 18 | -------------------------------------------------------------------------------- /library/src/main/res/layout-v14/layout_focus_marker.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 10 | 11 | 16 | 17 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /demo/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | #3F51B5 16 | #303F9F 17 | #4CAF50 18 | #212121 19 | #727272 20 | 21 | -------------------------------------------------------------------------------- /library/src/main/res/values/public.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /library/src/main/res/layout/surface_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /library/src/main/res/layout-v14/texture_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_flash_on.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 19 | 22 | 23 | -------------------------------------------------------------------------------- /library/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_flash_off.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 19 | 22 | 23 | -------------------------------------------------------------------------------- /demo/src/main/java/com/google/android/cameraview/demo/MainApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview.demo; 18 | 19 | import android.app.Application; 20 | 21 | import com.facebook.drawee.backends.pipeline.Fresco; 22 | 23 | /** 24 | * 25 | * Created by javayhu on 9/8/17. 26 | */ 27 | public class MainApplication extends Application { 28 | 29 | @Override 30 | public void onCreate() { 31 | super.onCreate(); 32 | 33 | Fresco.initialize(this); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_aspect_ratio.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 22 | 25 | 26 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_flash_auto.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 19 | 22 | 23 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/dialog_picture.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 23 | 24 | 28 | 29 | -------------------------------------------------------------------------------- /library/src/androidTest/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /library/src/androidTest/res/layout/activity_camera_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 18 | 19 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_switch_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 19 | 22 | 23 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | 20 | interface Constants { 21 | 22 | AspectRatio DEFAULT_ASPECT_RATIO = AspectRatio.of(16, 9);//如果是16:9的话显示图片的时候可以填充整个屏幕 23 | AspectRatio SECOND_ASPECT_RATIO = AspectRatio.of(4, 3);//如果是4:3的话显示图片的时候会上下留黑很多空间 24 | 25 | int FACING_BACK = 0; 26 | int FACING_FRONT = 1; 27 | 28 | int FLASH_OFF = 0; 29 | int FLASH_ON = 1; 30 | int FLASH_TORCH = 2; 31 | int FLASH_AUTO = 3; 32 | int FLASH_RED_EYE = 4; 33 | 34 | int LANDSCAPE_90 = 90; 35 | int LANDSCAPE_270 = 270; 36 | } 37 | -------------------------------------------------------------------------------- /demo/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 17 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 19 | 22 | 25 | 26 | -------------------------------------------------------------------------------- /demo/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 17 | 18 | 23 | 24 | 29 | 30 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /demo/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | CameraView Demo 16 | This app demonstrates the usage of CameraView. In order to do that, it needs permission to access camera. 17 | Camera app cannot do anything without camera permission. 18 | Picture taken 19 | Aspect ratio 20 | Switch flash 21 | Switch camera 22 | Flash auto 23 | Flash off 24 | Flash on 25 | 26 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/google/android/cameraview/CameraViewActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.app.Activity; 20 | import android.os.Bundle; 21 | 22 | import com.google.android.cameraview.test.R; 23 | 24 | public class CameraViewActivity extends Activity { 25 | 26 | private CameraView mCameraView; 27 | 28 | @Override 29 | protected void onCreate(Bundle savedInstanceState) { 30 | super.onCreate(savedInstanceState); 31 | setContentView(R.layout.activity_camera_view); 32 | mCameraView = (CameraView) findViewById(R.id.camera); 33 | } 34 | 35 | @Override 36 | protected void onResume() { 37 | super.onResume(); 38 | mCameraView.start(); 39 | } 40 | 41 | @Override 42 | protected void onPause() { 43 | mCameraView.stop(); 44 | super.onPause(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/google/android/cameraview/CameraViewMatchers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.support.annotation.NonNull; 20 | import android.view.View; 21 | 22 | import org.hamcrest.Description; 23 | import org.hamcrest.Matcher; 24 | import org.hamcrest.TypeSafeMatcher; 25 | 26 | class CameraViewMatchers { 27 | 28 | static Matcher hasAspectRatio(@NonNull final AspectRatio ratio) { 29 | return new TypeSafeMatcher() { 30 | @Override 31 | public void describeTo(Description description) { 32 | description.appendText("has aspect ratio of " + ratio); 33 | } 34 | 35 | @Override 36 | protected boolean matchesSafely(View view) { 37 | return ratio.equals(((CameraView) view).getAspectRatio()); 38 | } 39 | }; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /demo/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 16 | 17 | 20 | 21 | 28 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 9 | 10 | * If you are an individual writing original source code and you're sure you 11 | own the intellectual property, then you'll need to sign an [individual CLA] 12 | (https://cla.developers.google.com). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA] 15 | (https://cla.developers.google.com). 16 | 17 | Follow either of the two links above to access the appropriate CLA and 18 | instructions for how to sign and return it. Once we receive it, we'll be able to 19 | accept your pull requests. 20 | 21 | ## Contributing A Patch 22 | 23 | 1. Submit an issue describing your proposed change to the repo in question. 24 | 1. The repo owner will respond to your issue promptly. 25 | 1. If your proposed change is accepted, and you haven't already done so, sign a 26 | Contributor License Agreement (see details above). 27 | 1. Fork the desired repo, develop and test your code changes. 28 | 1. Ensure that your code adheres to the existing style in the sample to which 29 | you are contributing. Refer to the 30 | [Android Code Style Guide] 31 | (https://source.android.com/source/code-style.html) for the 32 | recommended coding standards for this organization. 33 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 34 | 1. Submit a pull request. 35 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/google/android/cameraview/CameraViewActions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; 20 | 21 | import android.support.annotation.NonNull; 22 | import android.support.test.espresso.UiController; 23 | import android.support.test.espresso.ViewAction; 24 | import android.view.View; 25 | 26 | import org.hamcrest.Matcher; 27 | 28 | class CameraViewActions { 29 | 30 | static ViewAction setAspectRatio(@NonNull final AspectRatio ratio) { 31 | return new ViewAction() { 32 | 33 | @Override 34 | public Matcher getConstraints() { 35 | return isAssignableFrom(CameraView.class); 36 | } 37 | 38 | @Override 39 | public String getDescription() { 40 | return "Set aspect ratio to " + ratio; 41 | } 42 | 43 | @Override 44 | public void perform(UiController controller, View view) { 45 | ((CameraView) view).setAspectRatio(ratio); 46 | } 47 | }; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /library/src/main/api23/com/google/android/cameraview/Camera2Api23.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.graphics.ImageFormat; 22 | import android.hardware.camera2.params.StreamConfigurationMap; 23 | 24 | /** 25 | * 在Android 6.0系统以上使用Camera2Api23作为CameraView的实现,它与Camera2的区别在于获取输出图片大小的方式略有不同 26 | */ 27 | @TargetApi(23) 28 | class Camera2Api23 extends Camera2 { 29 | 30 | Camera2Api23(Callback callback, PreviewImpl preview, Context context) { 31 | super(callback, preview, context); 32 | } 33 | 34 | @Override 35 | protected void collectPictureSizes(SizeMap sizes, StreamConfigurationMap map) { 36 | // Try to get hi-res output sizes 37 | android.util.Size[] outputSizes = map.getHighResolutionOutputSizes(ImageFormat.JPEG); 38 | if (outputSizes != null) { 39 | for (android.util.Size size : map.getHighResolutionOutputSizes(ImageFormat.JPEG)) { 40 | sizes.add(new Size(size.getWidth(), size.getHeight())); 41 | } 42 | } 43 | if (sizes.isEmpty()) { 44 | super.collectPictureSizes(sizes, map); 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /library/src/test/java/com/google/android/cameraview/SizeMapTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | import org.junit.Test; 23 | 24 | public class SizeMapTest { 25 | 26 | @Test 27 | public void testAdd_simple() { 28 | SizeMap map = new SizeMap(); 29 | map.add(new Size(3, 4)); 30 | map.add(new Size(9, 16)); 31 | assertThat(map.ratios().size(), is(2)); 32 | } 33 | 34 | @Test 35 | public void testAdd_duplicate() { 36 | SizeMap map = new SizeMap(); 37 | map.add(new Size(3, 4)); 38 | map.add(new Size(6, 8)); 39 | map.add(new Size(9, 12)); 40 | assertThat(map.ratios().size(), is(1)); 41 | AspectRatio ratio = (AspectRatio) map.ratios().toArray()[0]; 42 | assertThat(ratio.toString(), is("3:4")); 43 | assertThat(map.sizes(ratio).size(), is(3)); 44 | } 45 | 46 | @Test 47 | public void testClear() { 48 | SizeMap map = new SizeMap(); 49 | map.add(new Size(12, 34)); 50 | assertThat(map.ratios().size(), is(1)); 51 | map.clear(); 52 | assertThat(map.ratios().size(), is(0)); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /library/src/test/java/com/google/android/cameraview/SizeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | import org.junit.Test; 23 | 24 | import java.util.HashSet; 25 | 26 | public class SizeTest { 27 | 28 | @Test 29 | public void testGetters() { 30 | Size size = new Size(1, 2); 31 | assertThat(size.getWidth(), is(1)); 32 | assertThat(size.getHeight(), is(2)); 33 | } 34 | 35 | @Test 36 | public void testToString() { 37 | Size size = new Size(1, 2); 38 | assertThat(size.toString(), is("1x2")); 39 | } 40 | 41 | @Test 42 | public void testEquals() { 43 | Size a = new Size(1, 2); 44 | Size b = new Size(1, 2); 45 | Size c = new Size(3, 4); 46 | assertThat(a.equals(b), is(true)); 47 | assertThat(a.equals(c), is(false)); 48 | } 49 | 50 | @Test 51 | public void testHashCode() { 52 | int max = 100; 53 | HashSet codes = new HashSet<>(); 54 | for (int x = 1; x <= max; x++) { 55 | for (int y = 1; y <= max; y++) { 56 | codes.add(new Size(x, y).hashCode()); 57 | } 58 | } 59 | assertThat(codes.size(), is(max * max)); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/google/android/cameraview/AspectRatioIsCloseTo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static org.hamcrest.CoreMatchers.either; 20 | 21 | import org.hamcrest.Description; 22 | import org.hamcrest.Factory; 23 | import org.hamcrest.Matcher; 24 | import org.hamcrest.TypeSafeMatcher; 25 | 26 | public class AspectRatioIsCloseTo extends TypeSafeMatcher { 27 | 28 | private final AspectRatio mRatio; 29 | private final static float ERROR = 0.01f; 30 | 31 | public AspectRatioIsCloseTo(AspectRatio ratio) { 32 | mRatio = ratio; 33 | } 34 | 35 | @Override 36 | protected boolean matchesSafely(AspectRatio item) { 37 | float other = item.toFloat(); 38 | float self = mRatio.toFloat(); 39 | return self - ERROR < other && other < self + ERROR; 40 | } 41 | 42 | @Override 43 | public void describeTo(Description description) { 44 | description.appendText("an aspect ratio of ").appendValue(mRatio.toString()); 45 | } 46 | 47 | @Factory 48 | public static Matcher closeTo(AspectRatio ratio) { 49 | return new AspectRatioIsCloseTo(ratio); 50 | } 51 | 52 | @Factory 53 | public static Matcher closeToOrInverse(AspectRatio ratio) { 54 | return either(closeTo(ratio)).or(closeTo(ratio.inverse())); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /demo/build.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016 The Android Open Source Project 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | apply plugin: 'com.android.application' 16 | 17 | android { 18 | compileSdkVersion rootProject.ext.compileSdkVersion 19 | 20 | buildToolsVersion rootProject.ext.buildToolsVersion 21 | 22 | defaultConfig { 23 | applicationId 'com.google.android.cameraview.demo' 24 | minSdkVersion rootProject.ext.minSdkVersion 25 | targetSdkVersion rootProject.ext.targetSdkVersion 26 | versionCode 1 27 | versionName '1.0' 28 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' 29 | vectorDrawables.useSupportLibrary = true 30 | } 31 | buildTypes { 32 | release { 33 | minifyEnabled false 34 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 35 | } 36 | } 37 | } 38 | 39 | dependencies { 40 | compile fileTree(dir: 'libs', include: ['*.jar']) 41 | compile "com.android.support:design:$supportLibraryVersion" 42 | compile project(':library') 43 | 44 | compile 'com.facebook.fresco:fresco:1.5.0' 45 | 46 | // Tests 47 | testCompile 'junit:junit:4.12' 48 | androidTestCompile('com.android.support.test:runner:0.5') { 49 | exclude module: 'support-annotations' 50 | } 51 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') { 52 | exclude module: 'support-annotations' 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/google/android/cameraview/AspectRatioInstrumentationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static junit.framework.Assert.assertNotNull; 20 | 21 | import static org.hamcrest.MatcherAssert.assertThat; 22 | import static org.hamcrest.Matchers.sameInstance; 23 | import static org.hamcrest.core.Is.is; 24 | 25 | import android.os.Parcel; 26 | import android.support.test.runner.AndroidJUnit4; 27 | 28 | import org.junit.Test; 29 | import org.junit.runner.RunWith; 30 | 31 | 32 | @RunWith(AndroidJUnit4.class) 33 | public class AspectRatioInstrumentationTest { 34 | 35 | @Test 36 | public void testParcel() { 37 | final AspectRatio original = AspectRatio.of(4, 3); 38 | final Parcel parcel = Parcel.obtain(); 39 | try { 40 | parcel.writeParcelable(original, 0); 41 | parcel.setDataPosition(0); 42 | final AspectRatio restored = parcel.readParcelable(getClass().getClassLoader()); 43 | assertNotNull(restored); 44 | assertThat(restored.getX(), is(4)); 45 | assertThat(restored.getY(), is(3)); 46 | // As the first instance is alive, the parceled result should still be the same instance 47 | assertThat(restored, is(sameInstance(original))); 48 | } finally { 49 | parcel.recycle(); 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/CameraHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.content.Context; 20 | import android.content.SharedPreferences; 21 | 22 | /** 23 | * 相机辅助类 24 | * 25 | * Created by javayhu on 9/8/17. 26 | */ 27 | public class CameraHelper { 28 | 29 | private static CameraHelper sInstance; 30 | private static final String SP_NAME = "camera"; 31 | private static final String KEY_USE_CAMERA1 = "key_use_camera1"; 32 | 33 | private SharedPreferences mSharedPreferences; 34 | 35 | private CameraHelper(Context context) { 36 | mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); 37 | } 38 | 39 | public static CameraHelper getInstance(Context context) { 40 | if (sInstance == null) { 41 | sInstance = new CameraHelper(context); 42 | } 43 | return sInstance; 44 | } 45 | 46 | public void setUseCamera1InFuture() { 47 | if (mSharedPreferences != null) { 48 | mSharedPreferences.edit().putBoolean(KEY_USE_CAMERA1, true).apply(); 49 | } 50 | } 51 | 52 | //是否应该使用Camera1 API 53 | public boolean shouldUseCamera1() { 54 | if (mSharedPreferences != null) { 55 | return mSharedPreferences.getBoolean(KEY_USE_CAMERA1, false); 56 | } 57 | return false; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016 The Android Open Source Project 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | apply plugin: 'com.android.library' 16 | 17 | android { 18 | compileSdkVersion rootProject.ext.compileSdkVersion 19 | buildToolsVersion rootProject.ext.buildToolsVersion 20 | 21 | defaultConfig { 22 | minSdkVersion rootProject.ext.minSdkVersion 23 | targetSdkVersion rootProject.ext.targetSdkVersion 24 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' 25 | } 26 | buildTypes { 27 | release { 28 | minifyEnabled false 29 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 30 | } 31 | } 32 | sourceSets { 33 | main.java.srcDirs += 'src/main/base' 34 | main.java.srcDirs += 'src/main/api9' 35 | main.java.srcDirs += 'src/main/api14' 36 | main.java.srcDirs += 'src/main/api21' 37 | main.java.srcDirs += 'src/main/api23' 38 | } 39 | } 40 | 41 | dependencies { 42 | compile "com.android.support:support-annotations:$supportLibraryVersion" 43 | compile "com.android.support:support-v4:$supportLibraryVersion" 44 | 45 | // Tests 46 | testCompile 'junit:junit:4.12' 47 | androidTestCompile('com.android.support.test:runner:0.5') { 48 | exclude module: 'support-annotations' 49 | } 50 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') { 51 | exclude module: 'support-annotations' 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/PreviewImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.view.Surface; 20 | import android.view.SurfaceHolder; 21 | import android.view.View; 22 | 23 | 24 | /** 25 | * 不同方式实现Preview的抽象基类 26 | * 27 | * Encapsulates all the operations related to camera preview in a backward-compatible manner. 28 | */ 29 | abstract class PreviewImpl { 30 | 31 | private int mWidth; 32 | private int mHeight; 33 | private Callback mCallback; 34 | 35 | 36 | SurfaceHolder getSurfaceHolder() { 37 | return null; 38 | } 39 | 40 | Object getSurfaceTexture() { 41 | return null; 42 | } 43 | 44 | void setBufferSize(int width, int height) { 45 | } 46 | 47 | void setSize(int width, int height) { 48 | mWidth = width; 49 | mHeight = height; 50 | } 51 | 52 | int getWidth() { 53 | return mWidth; 54 | } 55 | 56 | int getHeight() { 57 | return mHeight; 58 | } 59 | 60 | void setCallback(Callback callback) { 61 | mCallback = callback; 62 | } 63 | 64 | void dispatchSurfaceChanged() { 65 | mCallback.onSurfaceChanged(); 66 | } 67 | 68 | 69 | /** 70 | * 抽象方法 71 | */ 72 | abstract Surface getSurface(); 73 | 74 | abstract View getView(); 75 | 76 | abstract Class getOutputClass(); 77 | 78 | abstract void setDisplayOrientation(int displayOrientation); 79 | 80 | abstract boolean isReady(); 81 | 82 | 83 | /** 84 | * surface变化时的回调 85 | */ 86 | interface Callback { 87 | void onSurfaceChanged(); 88 | } 89 | 90 | } 91 | 92 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 23 | 24 | 33 | 34 | 41 | 42 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /demo/src/main/res/layout-land/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 23 | 24 | 33 | 34 | 41 | 42 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/Size.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.support.annotation.NonNull; 20 | 21 | /** 22 | * 图像的宽和高 23 | * 24 | * Immutable class for describing width and height dimensions in pixels. 25 | */ 26 | public class Size implements Comparable { 27 | 28 | private final int mWidth; 29 | private final int mHeight; 30 | 31 | /** 32 | * Create a new immutable Size instance. 33 | * 34 | * @param width The width of the size, in pixels 35 | * @param height The height of the size, in pixels 36 | */ 37 | public Size(int width, int height) { 38 | mWidth = width; 39 | mHeight = height; 40 | } 41 | 42 | public int getWidth() { 43 | return mWidth; 44 | } 45 | 46 | public int getHeight() { 47 | return mHeight; 48 | } 49 | 50 | @Override 51 | public boolean equals(Object o) { 52 | if (o == null) { 53 | return false; 54 | } 55 | if (this == o) { 56 | return true; 57 | } 58 | if (o instanceof Size) { 59 | Size size = (Size) o; 60 | return mWidth == size.mWidth && mHeight == size.mHeight; 61 | } 62 | return false; 63 | } 64 | 65 | @Override 66 | public String toString() { 67 | return mWidth + " x " + mHeight; 68 | } 69 | 70 | @Override 71 | public int hashCode() { 72 | // assuming most sizes are <2^16, doing a rotate will give us perfect hashing 73 | return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); 74 | } 75 | 76 | @Override 77 | public int compareTo(@NonNull Size another) { 78 | return mWidth * mHeight - another.mWidth * another.mHeight; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CameraView 2 | 3 | ### 项目说明 4 | 5 | 这个项目基于Google的非正式开源的[CameraView](https://github.com/google/cameraview)组件,兼容Camera 1 API和Camera 2 API,提供了相机预览、切换前后摄像头、切换闪光灯、切换预览图片的比例以及拍照等功能。 6 | CameraView这个项目可以帮助Android开发者快速创建一个可以适配不同Android系统和不同Android设备,并且包含各种基本功能的相机界面,但是它是非正式的,所以仍然存在一些兼容性问题和bug,而且原开发者并没有试图再去修复了,这正创建是自己的CameraView项目的原因。 7 | 8 | 除上述CameraView原有项目自带的几个特性之外,这个项目主要做了以下几点改进: 9 | 10 | 1.参照[lin18/cameraview](https://github.com/lin18/cameraview)的源码加入了手动对焦功能,对焦的界面显示效果也比较容易修改和定制 11 | 12 | 2.修复原始的[CameraView](https://github.com/google/cameraview)组件中的几个bug,并提升了相机启动速度和拍照时的体验等问题 13 | 14 | 3.在相机模块的使用过程中提供了完整的日志输出,并且提供了便利的`LoggingDelegate`以便在release和debug模式之间轻松控制日志输出级别 15 | 16 | 详细的介绍以及Android端相机相关开发的经验请看[这篇文章](http://javayhu.me/blog/2017/09/25/camera-development-experience-on-android/) 17 | 18 | ### 应用界面 19 | 20 | ![img](cameraview_screenshot.png) 21 | 22 | ### 原始项目介绍 23 | 24 | 下面是[CameraView](https://github.com/google/cameraview)组件的原始说明文档,我觉得其中有个小错误,API Level为24的时候的`Preview View`是`TextureView`,原始文档写的是`SurfaceView` 25 | 26 | *This is a preview release. The API is subject to change.* 27 | 28 | This is not an official Google product. 29 | 30 | CameraView aims to help Android developers easily integrate Camera features. 31 | 32 | Requires API Level 9. The library uses Camera 1 API on API Level 9-20 and Camera2 on 21 and above. 33 | 34 | | API Level | Camera API | Preview View | 35 | |:---------:|------------|--------------| 36 | | 9-13 | Camera1 | SurfaceView | 37 | | 14-20 | Camera1 | TextureView | 38 | | 21-23 | Camera2 | TextureView | 39 | | 24 | Camera2 | TextureView | 40 | 41 | ## Features 42 | 43 | - Camera preview by placing it in a layout XML (and calling the start method) 44 | - Configuration by attributes 45 | - Aspect ratio (app:aspectRatio) 46 | - Auto-focus (app:autoFocus) 47 | - Flash (app:flash) 48 | 49 | ## Usage 50 | 51 | ```xml 52 | 62 | ``` 63 | 64 | ```java 65 | @Override 66 | protected void onResume() { 67 | super.onResume(); 68 | mCameraView.start(); 69 | } 70 | 71 | @Override 72 | protected void onPause() { 73 | mCameraView.stop(); 74 | super.onPause(); 75 | } 76 | ``` 77 | 78 | You can see a complete usage in the demo app. 79 | 80 | ## Contribution 81 | 82 | See [CONTRIBUTING.md](/CONTRIBUTING.md). 83 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /library/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 40 | 41 | 45 | 46 | 51 | 52 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /demo/src/main/java/com/google/android/cameraview/demo/PictureDialogFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview.demo; 18 | 19 | import android.app.Dialog; 20 | import android.net.Uri; 21 | import android.support.v4.app.DialogFragment; 22 | import android.os.Bundle; 23 | import android.support.annotation.NonNull; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.Window; 27 | import android.view.WindowManager; 28 | 29 | import com.facebook.drawee.view.SimpleDraweeView; 30 | 31 | import java.io.File; 32 | 33 | public class PictureDialogFragment extends DialogFragment { 34 | 35 | private static final String ARG_FILE_PATH = "file_path"; 36 | 37 | private SimpleDraweeView mImageView; 38 | 39 | public static PictureDialogFragment newInstance(String filePath) { 40 | PictureDialogFragment fragment = new PictureDialogFragment(); 41 | Bundle args = new Bundle(); 42 | args.putString(ARG_FILE_PATH, filePath); 43 | fragment.setArguments(args); 44 | return fragment; 45 | } 46 | 47 | @NonNull 48 | @Override 49 | public Dialog onCreateDialog(Bundle savedInstanceState) { 50 | final Bundle args = getArguments(); 51 | String filePath = args.getString(ARG_FILE_PATH); 52 | Uri uri = Uri.fromFile(new File(filePath)); 53 | 54 | View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_picture, null); 55 | mImageView = (SimpleDraweeView) contentView.findViewById(R.id.image); 56 | mImageView.setImageURI(uri); 57 | 58 | Dialog dialog = new Dialog(getContext()); 59 | dialog.setCancelable(true); 60 | dialog.setCanceledOnTouchOutside(true); 61 | dialog.setContentView(contentView); 62 | 63 | //make dialog fullscreen 64 | Window window = dialog.getWindow(); 65 | window.getDecorView().setPadding(0, 0, 0, 0);//消除边距 66 | WindowManager.LayoutParams layoutParams = window.getAttributes(); 67 | layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; 68 | layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; 69 | window.setAttributes(layoutParams); 70 | 71 | return dialog; 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /library/src/main/api9/com/google/android/cameraview/SurfaceViewPreview.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.content.Context; 20 | import android.support.v4.view.ViewCompat; 21 | import android.view.Surface; 22 | import android.view.SurfaceHolder; 23 | import android.view.SurfaceView; 24 | import android.view.View; 25 | import android.view.ViewGroup; 26 | 27 | /** 28 | * Android API版本在9到14之间用SurfaceViewPreview 29 | */ 30 | class SurfaceViewPreview extends PreviewImpl { 31 | 32 | private final SurfaceView mSurfaceView; 33 | 34 | SurfaceViewPreview(Context context, ViewGroup parent) { 35 | final View view = View.inflate(context, R.layout.surface_view, parent); 36 | mSurfaceView = (SurfaceView) view.findViewById(R.id.surface_view); 37 | final SurfaceHolder holder = mSurfaceView.getHolder(); 38 | //noinspection deprecation 39 | holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 40 | holder.addCallback(new SurfaceHolder.Callback() { 41 | @Override 42 | public void surfaceCreated(SurfaceHolder h) { 43 | } 44 | 45 | @Override 46 | public void surfaceChanged(SurfaceHolder h, int format, int width, int height) { 47 | setSize(width, height); 48 | if (!ViewCompat.isInLayout(mSurfaceView)) { 49 | dispatchSurfaceChanged(); 50 | } 51 | } 52 | 53 | @Override 54 | public void surfaceDestroyed(SurfaceHolder h) { 55 | setSize(0, 0); 56 | } 57 | }); 58 | } 59 | 60 | @Override 61 | Surface getSurface() { 62 | return getSurfaceHolder().getSurface(); 63 | } 64 | 65 | @Override 66 | SurfaceHolder getSurfaceHolder() { 67 | return mSurfaceView.getHolder(); 68 | } 69 | 70 | @Override 71 | View getView() { 72 | return mSurfaceView; 73 | } 74 | 75 | @Override 76 | Class getOutputClass() { 77 | return SurfaceHolder.class; 78 | } 79 | 80 | @Override 81 | void setDisplayOrientation(int displayOrientation) { 82 | } 83 | 84 | @Override 85 | boolean isReady() { 86 | return getWidth() != 0 && getHeight() != 0; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/CameraViewImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.view.View; 20 | 21 | import java.util.Set; 22 | 23 | /** 24 | * 不同方式实现CameraView的抽象基类 25 | */ 26 | abstract class CameraViewImpl { 27 | 28 | public static final int FOCUS_AREA_SIZE_DEFAULT = 300; 29 | public static final int FOCUS_METERING_AREA_WEIGHT_DEFAULT = 1000; 30 | public static final int DELAY_MILLIS_BEFORE_RESETTING_FOCUS = 3000; 31 | 32 | protected final Callback mCallback; 33 | protected final PreviewImpl mPreview; 34 | 35 | CameraViewImpl(Callback callback, PreviewImpl preview) { 36 | mCallback = callback; 37 | mPreview = preview; 38 | } 39 | 40 | View getView() { 41 | return mPreview.getView(); 42 | } 43 | 44 | int getFocusAreaSize() { 45 | return FOCUS_AREA_SIZE_DEFAULT; 46 | } 47 | 48 | int getFocusMeteringAreaWeight() { 49 | return FOCUS_METERING_AREA_WEIGHT_DEFAULT; 50 | } 51 | 52 | void detachFocusTapListener() { 53 | if (mPreview != null && mPreview.getView() != null) { 54 | mPreview.getView().setOnTouchListener(null); 55 | } 56 | } 57 | 58 | 59 | /** 60 | * 抽象方法 61 | */ 62 | abstract boolean start(); 63 | 64 | abstract void stop(); 65 | 66 | abstract boolean isCameraOpened(); 67 | 68 | abstract void setFacing(int facing); 69 | 70 | abstract int getFacing(); 71 | 72 | abstract Set getSupportedAspectRatios(); 73 | 74 | abstract boolean setAspectRatio(AspectRatio ratio); 75 | 76 | abstract AspectRatio getAspectRatio(); 77 | 78 | abstract void setAutoFocus(boolean autoFocus); 79 | 80 | abstract boolean getAutoFocus(); 81 | 82 | abstract void setFlash(int flash); 83 | 84 | abstract int getFlash(); 85 | 86 | abstract void takePicture(); 87 | 88 | abstract void setDisplayOrientation(int displayOrientation); 89 | 90 | 91 | /** 92 | * 摄像头相关回调 (camera session callbacks) 93 | */ 94 | interface Callback { 95 | 96 | void onCameraOpened(); 97 | 98 | void onCameraClosed(); 99 | 100 | void onPictureTaken(byte[] data); 101 | } 102 | 103 | } 104 | 105 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/SizeMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.support.v4.util.ArrayMap; 20 | 21 | import java.util.Set; 22 | import java.util.SortedSet; 23 | import java.util.TreeSet; 24 | 25 | /** 26 | * 从宽高比到图像size的映射,key是宽高比,value是满足这个宽高比的图像size集合 27 | * 28 | * A collection class that automatically groups {@link Size}s by their {@link AspectRatio}s. 29 | */ 30 | class SizeMap { 31 | 32 | private final ArrayMap> mRatios = new ArrayMap<>(); 33 | 34 | /** 35 | * Add a new {@link Size} to this collection. 36 | * 37 | * @param size The size to add. 38 | * @return {@code true} if it is added, {@code false} if it already exists and is not added. 39 | */ 40 | public boolean add(Size size) { 41 | for (AspectRatio ratio : mRatios.keySet()) { 42 | if (ratio.matches(size)) { 43 | final SortedSet sizes = mRatios.get(ratio); 44 | if (sizes.contains(size)) { 45 | return false; 46 | } else { 47 | sizes.add(size); 48 | return true; 49 | } 50 | } 51 | } 52 | // None of the existing ratio matches the provided size; add a new key 53 | SortedSet sizes = new TreeSet<>(); 54 | sizes.add(size); 55 | mRatios.put(AspectRatio.of(size.getWidth(), size.getHeight()), sizes); 56 | return true; 57 | } 58 | 59 | /** 60 | * Removes the specified aspect ratio and all sizes associated with it. 61 | */ 62 | public void remove(AspectRatio ratio) { 63 | mRatios.remove(ratio); 64 | } 65 | 66 | public Set ratios() { 67 | return mRatios.keySet(); 68 | } 69 | 70 | public SortedSet sizes(AspectRatio ratio) { 71 | return mRatios.get(ratio); 72 | } 73 | 74 | public void clear() { 75 | mRatios.clear(); 76 | } 77 | 78 | public boolean isEmpty() { 79 | return mRatios.isEmpty(); 80 | } 81 | 82 | @Override 83 | public String toString() { 84 | StringBuilder builder = new StringBuilder(""); 85 | Set ratioSet = ratios(); 86 | for (AspectRatio ratio: ratioSet) { 87 | SortedSet sizeSet = sizes(ratio); 88 | builder.append("[").append(ratio.toString()).append("]:{"); 89 | for (Size size : sizeSet) { 90 | builder.append(size.toString()).append(", "); 91 | } 92 | builder.append("}; "); 93 | } 94 | return builder.toString(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/FocusMarkerView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.animation.Animator; 20 | import android.animation.AnimatorListenerAdapter; 21 | import android.annotation.TargetApi; 22 | import android.content.Context; 23 | import android.support.annotation.NonNull; 24 | import android.support.annotation.Nullable; 25 | import android.util.AttributeSet; 26 | import android.view.LayoutInflater; 27 | import android.widget.FrameLayout; 28 | import android.widget.ImageView; 29 | 30 | /** 31 | * 手动对焦的框框组件 32 | */ 33 | @TargetApi(14) 34 | public class FocusMarkerView extends FrameLayout { 35 | 36 | private FrameLayout mFocusMarkerContainer; 37 | private ImageView mFill; 38 | 39 | public FocusMarkerView(@NonNull Context context) { 40 | this(context, null); 41 | } 42 | 43 | public FocusMarkerView(@NonNull Context context, @Nullable AttributeSet attrs) { 44 | super(context, attrs); 45 | LayoutInflater.from(getContext()).inflate(R.layout.layout_focus_marker, this); 46 | 47 | mFocusMarkerContainer = (FrameLayout) findViewById(R.id.focusMarkerContainer); 48 | mFill = (ImageView) findViewById(R.id.fill); 49 | 50 | mFocusMarkerContainer.setAlpha(0); 51 | } 52 | 53 | public void focus(float mx, float my) { 54 | int x = (int) (mx - mFocusMarkerContainer.getWidth() / 2); 55 | int y = (int) (my - mFocusMarkerContainer.getWidth() / 2); 56 | 57 | mFocusMarkerContainer.setTranslationX(x); 58 | mFocusMarkerContainer.setTranslationY(y); 59 | 60 | mFocusMarkerContainer.animate().setListener(null).cancel(); 61 | mFill.animate().setListener(null).cancel(); 62 | 63 | mFill.setScaleX(0); 64 | mFill.setScaleY(0); 65 | mFill.setAlpha(1f); 66 | 67 | mFocusMarkerContainer.setScaleX(1.36f); 68 | mFocusMarkerContainer.setScaleY(1.36f); 69 | mFocusMarkerContainer.setAlpha(1f); 70 | 71 | mFocusMarkerContainer.animate().scaleX(1).scaleY(1).setStartDelay(0).setDuration(330) 72 | .setListener(new AnimatorListenerAdapter() { 73 | @Override 74 | public void onAnimationEnd(Animator animation) { 75 | super.onAnimationEnd(animation); 76 | mFocusMarkerContainer.animate().alpha(0).setStartDelay(750).setDuration(800).setListener(null).start(); 77 | } 78 | }).start(); 79 | 80 | mFill.animate().scaleX(1).scaleY(1).setDuration(330) 81 | .setListener(new AnimatorListenerAdapter() { 82 | @Override 83 | public void onAnimationEnd(Animator animation) { 84 | super.onAnimationEnd(animation); 85 | mFill.animate().alpha(0).setDuration(800).setListener(null).start(); 86 | } 87 | }).start(); 88 | 89 | } 90 | 91 | 92 | } 93 | -------------------------------------------------------------------------------- /library/src/test/java/com/google/android/cameraview/AspectRatioTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import static org.hamcrest.CoreMatchers.is; 20 | import static org.junit.Assert.assertThat; 21 | 22 | import org.junit.Test; 23 | 24 | import java.util.HashSet; 25 | 26 | public class AspectRatioTest { 27 | 28 | @Test 29 | public void testGcd() { 30 | AspectRatio r; 31 | r = AspectRatio.of(1, 2); 32 | assertThat(r.getX(), is(1)); 33 | r = AspectRatio.of(2, 4); 34 | assertThat(r.getX(), is(1)); 35 | assertThat(r.getY(), is(2)); 36 | r = AspectRatio.of(391, 713); 37 | assertThat(r.getX(), is(17)); 38 | assertThat(r.getY(), is(31)); 39 | } 40 | 41 | @Test 42 | public void testMatches() { 43 | AspectRatio ratio = AspectRatio.of(3, 4); 44 | assertThat(ratio.matches(new Size(6, 8)), is(true)); 45 | assertThat(ratio.matches(new Size(1, 2)), is(false)); 46 | } 47 | 48 | @Test 49 | public void testGetters() { 50 | AspectRatio ratio = AspectRatio.of(2, 4); // Reduced to 1:2 51 | assertThat(ratio.getX(), is(1)); 52 | assertThat(ratio.getY(), is(2)); 53 | } 54 | 55 | @Test 56 | public void testToString() { 57 | AspectRatio ratio = AspectRatio.of(1, 2); 58 | assertThat(ratio.toString(), is("1:2")); 59 | } 60 | 61 | @Test 62 | public void testEquals() { 63 | AspectRatio a = AspectRatio.of(1, 2); 64 | AspectRatio b = AspectRatio.of(2, 4); 65 | AspectRatio c = AspectRatio.of(2, 3); 66 | assertThat(a.equals(b), is(true)); 67 | assertThat(a.equals(c), is(false)); 68 | } 69 | 70 | @Test 71 | public void testHashCode() { 72 | int max = 100; 73 | HashSet codes = new HashSet<>(); 74 | for (int x = 1; x <= 100; x++) { 75 | codes.add(AspectRatio.of(x, 1).hashCode()); 76 | } 77 | assertThat(codes.size(), is(max)); 78 | codes.clear(); 79 | for (int y = 1; y <= 100; y++) { 80 | codes.add(AspectRatio.of(1, y).hashCode()); 81 | } 82 | assertThat(codes.size(), is(max)); 83 | } 84 | 85 | @Test 86 | public void testInverse() { 87 | AspectRatio r = AspectRatio.of(4, 3); 88 | assertThat(r.getX(), is(4)); 89 | assertThat(r.getY(), is(3)); 90 | AspectRatio s = r.inverse(); 91 | assertThat(s.getX(), is(3)); 92 | assertThat(s.getY(), is(4)); 93 | } 94 | 95 | @Test 96 | public void testParse() { 97 | AspectRatio r = AspectRatio.parse("23:31"); 98 | assertThat(r.getX(), is(23)); 99 | assertThat(r.getY(), is(31)); 100 | } 101 | 102 | @Test(expected = IllegalArgumentException.class) 103 | public void testParseFailure() { 104 | AspectRatio.parse("MALFORMED"); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/DisplayOrientationDetector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.content.Context; 20 | import android.util.SparseIntArray; 21 | import android.view.Display; 22 | import android.view.OrientationEventListener; 23 | import android.view.Surface; 24 | 25 | 26 | /** 27 | * Monitors the value returned from {@link Display#getRotation()}. 28 | */ 29 | abstract class DisplayOrientationDetector { 30 | 31 | private final OrientationEventListener mOrientationEventListener; 32 | 33 | /** Mapping from Surface.Rotation_n to degrees. */ 34 | private static final SparseIntArray DISPLAY_ORIENTATIONS = new SparseIntArray(); 35 | 36 | static { 37 | DISPLAY_ORIENTATIONS.put(Surface.ROTATION_0, 0); 38 | DISPLAY_ORIENTATIONS.put(Surface.ROTATION_90, 90); 39 | DISPLAY_ORIENTATIONS.put(Surface.ROTATION_180, 180); 40 | DISPLAY_ORIENTATIONS.put(Surface.ROTATION_270, 270); 41 | } 42 | 43 | private Display mDisplay; 44 | 45 | private int mLastKnownDisplayOrientation = 0; 46 | 47 | public DisplayOrientationDetector(Context context) { 48 | mOrientationEventListener = new OrientationEventListener(context) { 49 | 50 | /** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */ 51 | private int mLastKnownRotation = -1; 52 | 53 | @Override 54 | public void onOrientationChanged(int orientation) { 55 | if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN || 56 | mDisplay == null) { 57 | return; 58 | } 59 | final int rotation = mDisplay.getRotation(); 60 | if (mLastKnownRotation != rotation) { 61 | mLastKnownRotation = rotation; 62 | dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation)); 63 | } 64 | } 65 | }; 66 | } 67 | 68 | public void enable(Display display) { 69 | mDisplay = display; 70 | mOrientationEventListener.enable(); 71 | // Immediately dispatch the first callback 72 | dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(display.getRotation())); 73 | } 74 | 75 | public void disable() { 76 | mOrientationEventListener.disable(); 77 | mDisplay = null; 78 | } 79 | 80 | public int getLastKnownDisplayOrientation() { 81 | return mLastKnownDisplayOrientation; 82 | } 83 | 84 | private void dispatchOnDisplayOrientationChanged(int displayOrientation) { 85 | mLastKnownDisplayOrientation = displayOrientation; 86 | onDisplayOrientationChanged(displayOrientation); 87 | } 88 | 89 | /** 90 | * Called when display orientation is changed. 91 | * 92 | * @param displayOrientation One of 0, 90, 180, and 270. 93 | */ 94 | public abstract void onDisplayOrientationChanged(int displayOrientation); 95 | 96 | } 97 | -------------------------------------------------------------------------------- /demo/src/main/java/com/google/android/cameraview/demo/ConfirmationDialogFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview.demo; 18 | 19 | import android.app.Dialog; 20 | import android.content.DialogInterface; 21 | import android.os.Bundle; 22 | import android.support.annotation.NonNull; 23 | import android.support.annotation.StringRes; 24 | import android.support.v4.app.ActivityCompat; 25 | import android.support.v4.app.DialogFragment; 26 | import android.support.v7.app.AlertDialog; 27 | import android.widget.Toast; 28 | 29 | public class ConfirmationDialogFragment extends DialogFragment { 30 | 31 | private static final String ARG_MESSAGE = "message"; 32 | private static final String ARG_PERMISSIONS = "permissions"; 33 | private static final String ARG_REQUEST_CODE = "request_code"; 34 | private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message"; 35 | 36 | public static ConfirmationDialogFragment newInstance(@StringRes int message, String[] permissions, int requestCode, @StringRes int notGrantedMessage) { 37 | ConfirmationDialogFragment fragment = new ConfirmationDialogFragment(); 38 | Bundle args = new Bundle(); 39 | args.putInt(ARG_MESSAGE, message); 40 | args.putStringArray(ARG_PERMISSIONS, permissions); 41 | args.putInt(ARG_REQUEST_CODE, requestCode); 42 | args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage); 43 | fragment.setArguments(args); 44 | return fragment; 45 | } 46 | 47 | @NonNull 48 | @Override 49 | public Dialog onCreateDialog(Bundle savedInstanceState) { 50 | final Bundle args = getArguments(); 51 | return new AlertDialog.Builder(getActivity()) 52 | .setMessage(args.getInt(ARG_MESSAGE)) 53 | .setPositiveButton(android.R.string.ok, 54 | new DialogInterface.OnClickListener() { 55 | @Override 56 | public void onClick(DialogInterface dialog, int which) { 57 | String[] permissions = args.getStringArray(ARG_PERMISSIONS); 58 | if (permissions == null) { 59 | throw new IllegalArgumentException(); 60 | } 61 | ActivityCompat.requestPermissions(getActivity(), permissions, args.getInt(ARG_REQUEST_CODE)); 62 | } 63 | }) 64 | .setNegativeButton(android.R.string.cancel, 65 | new DialogInterface.OnClickListener() { 66 | @Override 67 | public void onClick(DialogInterface dialog, int which) { 68 | Toast.makeText(getActivity(), args.getInt(ARG_NOT_GRANTED_MESSAGE), Toast.LENGTH_SHORT).show(); 69 | } 70 | }) 71 | .create(); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/CameraLogDefaultLoggingDelegate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.util.Log; 20 | 21 | import java.io.PrintWriter; 22 | import java.io.StringWriter; 23 | 24 | /** 25 | * LoggingDelegate的默认实现就是println方式输出日志 26 | * 27 | * Created by javayhu on 8/19/17. 28 | */ 29 | public class CameraLogDefaultLoggingDelegate implements LoggingDelegate { 30 | 31 | public static final CameraLogDefaultLoggingDelegate sInstance = 32 | new CameraLogDefaultLoggingDelegate(); 33 | 34 | private String mApplicationTag = "camera"; 35 | private int mMinimumLoggingLevel = Log.INFO; 36 | 37 | private CameraLogDefaultLoggingDelegate() { 38 | } 39 | 40 | public static CameraLogDefaultLoggingDelegate getInstance() { 41 | return sInstance; 42 | } 43 | 44 | private static String getMsg(String msg, Throwable tr) { 45 | return msg + '\n' + getStackTraceString(tr); 46 | } 47 | 48 | private static String getStackTraceString(Throwable tr) { 49 | if (tr == null) { 50 | return ""; 51 | } 52 | StringWriter sw = new StringWriter(); 53 | PrintWriter pw = new PrintWriter(sw); 54 | tr.printStackTrace(pw); 55 | return sw.toString(); 56 | } 57 | 58 | /** 59 | * Sets an application tag that is used for checking if a log line is loggable and also 60 | * to prefix to all log lines. 61 | * 62 | * @param tag the tag 63 | */ 64 | public void setApplicationTag(String tag) { 65 | mApplicationTag = tag; 66 | } 67 | 68 | @Override 69 | public int getMinimumLoggingLevel() { 70 | return mMinimumLoggingLevel; 71 | } 72 | 73 | @Override 74 | public void setMinimumLoggingLevel(int level) { 75 | mMinimumLoggingLevel = level; 76 | } 77 | 78 | @Override 79 | public boolean isLoggable(int level) { 80 | return mMinimumLoggingLevel <= level; 81 | } 82 | 83 | @Override 84 | public void v(String tag, String msg) { 85 | println(Log.VERBOSE, tag, msg); 86 | } 87 | 88 | @Override 89 | public void v(String tag, String msg, Throwable tr) { 90 | println(Log.VERBOSE, tag, msg, tr); 91 | } 92 | 93 | @Override 94 | public void d(String tag, String msg) { 95 | println(Log.DEBUG, tag, msg); 96 | } 97 | 98 | @Override 99 | public void d(String tag, String msg, Throwable tr) { 100 | println(Log.DEBUG, tag, msg, tr); 101 | } 102 | 103 | @Override 104 | public void i(String tag, String msg) { 105 | println(Log.INFO, tag, msg); 106 | } 107 | 108 | @Override 109 | public void i(String tag, String msg, Throwable tr) { 110 | println(Log.INFO, tag, msg, tr); 111 | } 112 | 113 | @Override 114 | public void w(String tag, String msg) { 115 | println(Log.WARN, tag, msg); 116 | } 117 | 118 | @Override 119 | public void w(String tag, String msg, Throwable tr) { 120 | println(Log.WARN, tag, msg, tr); 121 | } 122 | 123 | @Override 124 | public void e(String tag, String msg) { 125 | println(Log.ERROR, tag, msg); 126 | } 127 | 128 | @Override 129 | public void e(String tag, String msg, Throwable tr) { 130 | println(Log.ERROR, tag, msg, tr); 131 | } 132 | 133 | /** 134 | *

Note: this gets forwarded to {@code android.util.Log.e} as {@code android.util.Log.wtf} 135 | * might crash the app. 136 | */ 137 | @Override 138 | public void wtf(String tag, String msg) { 139 | println(Log.ERROR, tag, msg); 140 | } 141 | 142 | /** 143 | *

Note: this gets forwarded to {@code android.util.Log.e} as {@code android.util.Log.wtf} 144 | * might crash the app. 145 | */ 146 | @Override 147 | public void wtf(String tag, String msg, Throwable tr) { 148 | println(Log.ERROR, tag, msg, tr); 149 | } 150 | 151 | @Override 152 | public void log(int priority, String tag, String msg) { 153 | println(priority, tag, msg); 154 | } 155 | 156 | private void println(int priority, String tag, String msg) { 157 | Log.println(priority, prefixTag(tag), msg); 158 | } 159 | 160 | private void println(int priority, String tag, String msg, Throwable tr) { 161 | Log.println(priority, prefixTag(tag), getMsg(msg, tr)); 162 | } 163 | 164 | private String prefixTag(String tag) { 165 | if (mApplicationTag != null) { 166 | return mApplicationTag + ":" + tag; 167 | } else { 168 | return tag; 169 | } 170 | } 171 | } -------------------------------------------------------------------------------- /demo/src/main/java/com/google/android/cameraview/demo/AspectRatioFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview.demo; 18 | 19 | import android.app.Dialog; 20 | import android.content.Context; 21 | import android.content.DialogInterface; 22 | import android.os.Bundle; 23 | import android.support.annotation.NonNull; 24 | import android.support.v4.app.DialogFragment; 25 | import android.support.v7.app.AlertDialog; 26 | import android.view.LayoutInflater; 27 | import android.view.View; 28 | import android.view.ViewGroup; 29 | import android.widget.BaseAdapter; 30 | import android.widget.TextView; 31 | 32 | import com.google.android.cameraview.AspectRatio; 33 | 34 | import java.util.Arrays; 35 | import java.util.Set; 36 | 37 | 38 | /** 39 | * A simple dialog that allows user to pick an aspect ratio. 40 | */ 41 | public class AspectRatioFragment extends DialogFragment { 42 | 43 | private static final String ARG_ASPECT_RATIOS = "aspect_ratios"; 44 | private static final String ARG_CURRENT_ASPECT_RATIO = "current_aspect_ratio"; 45 | 46 | private Listener mListener; 47 | 48 | public static AspectRatioFragment newInstance(Set ratios, AspectRatio currentRatio) { 49 | final AspectRatioFragment fragment = new AspectRatioFragment(); 50 | final Bundle args = new Bundle(); 51 | args.putParcelableArray(ARG_ASPECT_RATIOS, ratios.toArray(new AspectRatio[ratios.size()])); 52 | args.putParcelable(ARG_CURRENT_ASPECT_RATIO, currentRatio); 53 | fragment.setArguments(args); 54 | return fragment; 55 | } 56 | 57 | @Override 58 | public void onAttach(Context context) { 59 | super.onAttach(context); 60 | mListener = (Listener) context; 61 | } 62 | 63 | @Override 64 | public void onDetach() { 65 | mListener = null; 66 | super.onDetach(); 67 | } 68 | 69 | @NonNull 70 | @Override 71 | public Dialog onCreateDialog(Bundle savedInstanceState) { 72 | final Bundle args = getArguments(); 73 | final AspectRatio[] ratios = (AspectRatio[]) args.getParcelableArray(ARG_ASPECT_RATIOS); 74 | if (ratios == null) { 75 | throw new RuntimeException("No ratios"); 76 | } 77 | Arrays.sort(ratios); 78 | final AspectRatio current = args.getParcelable(ARG_CURRENT_ASPECT_RATIO); 79 | final AspectRatioAdapter adapter = new AspectRatioAdapter(ratios, current); 80 | return new AlertDialog.Builder(getActivity()) 81 | .setAdapter(adapter, new DialogInterface.OnClickListener() { 82 | @Override 83 | public void onClick(DialogInterface dialog, int position) { 84 | mListener.onAspectRatioSelected(ratios[position]); 85 | } 86 | }) 87 | .create(); 88 | } 89 | 90 | private static class AspectRatioAdapter extends BaseAdapter { 91 | 92 | private final AspectRatio[] mRatios; 93 | private final AspectRatio mCurrentRatio; 94 | 95 | AspectRatioAdapter(AspectRatio[] ratios, AspectRatio current) { 96 | mRatios = ratios; 97 | mCurrentRatio = current; 98 | } 99 | 100 | @Override 101 | public int getCount() { 102 | return mRatios.length; 103 | } 104 | 105 | @Override 106 | public AspectRatio getItem(int position) { 107 | return mRatios[position]; 108 | } 109 | 110 | @Override 111 | public long getItemId(int position) { 112 | return getItem(position).hashCode(); 113 | } 114 | 115 | @Override 116 | public View getView(int position, View view, ViewGroup parent) { 117 | AspectRatioAdapter.ViewHolder holder; 118 | if (view == null) { 119 | view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); 120 | holder = new AspectRatioAdapter.ViewHolder(); 121 | holder.text = (TextView) view.findViewById(android.R.id.text1); 122 | view.setTag(holder); 123 | } else { 124 | holder = (AspectRatioAdapter.ViewHolder) view.getTag(); 125 | } 126 | AspectRatio ratio = getItem(position); 127 | StringBuilder sb = new StringBuilder(ratio.toString()); 128 | if (ratio.equals(mCurrentRatio)) { 129 | sb.append(" *"); 130 | } 131 | holder.text.setText(sb); 132 | return view; 133 | } 134 | 135 | private static class ViewHolder { 136 | TextView text; 137 | } 138 | 139 | } 140 | 141 | public interface Listener { 142 | void onAspectRatioSelected(@NonNull AspectRatio ratio); 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /library/src/main/api14/com/google/android/cameraview/TextureViewPreview.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.graphics.Matrix; 22 | import android.graphics.SurfaceTexture; 23 | import android.view.Surface; 24 | import android.view.TextureView; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | 28 | /** 29 | * Android系统从4.0 (API 14)版本开始引入了TextureView,比SurfaceView更加强大 30 | */ 31 | @TargetApi(14) 32 | class TextureViewPreview extends PreviewImpl { 33 | 34 | private static final String TAG = TextureViewPreview.class.getSimpleName(); 35 | 36 | private final TextureView mTextureView; 37 | 38 | private int mDisplayOrientation; 39 | 40 | TextureViewPreview(Context context, ViewGroup parent) { 41 | final View view = View.inflate(context, R.layout.texture_view, parent); 42 | mTextureView = (TextureView) view.findViewById(R.id.texture_view); 43 | mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { 44 | 45 | @Override 46 | public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { 47 | CameraLog.i(TAG, "onSurfaceTextureAvailable, width = %d, height = %d", width, height);//width = 1605, height = 2140 48 | setSize(width, height); 49 | configureTransform(); 50 | dispatchSurfaceChanged(); 51 | } 52 | 53 | @Override 54 | public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { 55 | CameraLog.i(TAG, "onSurfaceTextureSizeChanged, width = %d, height = %d", width, height); 56 | setSize(width, height); 57 | configureTransform(); 58 | dispatchSurfaceChanged(); 59 | } 60 | 61 | @Override 62 | public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { 63 | CameraLog.i(TAG, "onSurfaceTextureDestroyed"); 64 | setSize(0, 0); 65 | return true; 66 | } 67 | 68 | @Override 69 | public void onSurfaceTextureUpdated(SurfaceTexture surface) { 70 | } 71 | }); 72 | } 73 | 74 | // This method is called only from Camera2. 75 | @TargetApi(15) 76 | @Override 77 | void setBufferSize(int width, int height) { 78 | mTextureView.getSurfaceTexture().setDefaultBufferSize(width, height); 79 | } 80 | 81 | @Override 82 | Surface getSurface() { 83 | return new Surface(mTextureView.getSurfaceTexture()); 84 | } 85 | 86 | @Override 87 | SurfaceTexture getSurfaceTexture() { 88 | return mTextureView.getSurfaceTexture(); 89 | } 90 | 91 | @Override 92 | View getView() { 93 | return mTextureView; 94 | } 95 | 96 | @Override 97 | Class getOutputClass() { 98 | return SurfaceTexture.class; 99 | } 100 | 101 | @Override 102 | void setDisplayOrientation(int displayOrientation) { 103 | mDisplayOrientation = displayOrientation; 104 | configureTransform(); 105 | } 106 | 107 | @Override 108 | boolean isReady() { 109 | return mTextureView.getSurfaceTexture() != null; 110 | } 111 | 112 | /** 113 | * Configures the transform matrix for TextureView based on {@link #mDisplayOrientation} and 114 | * the surface size. 115 | */ 116 | private void configureTransform() { 117 | Matrix matrix = new Matrix(); 118 | if (mDisplayOrientation % 180 == 90) { 119 | final int width = getWidth(); 120 | final int height = getHeight(); 121 | // Rotate the camera preview when the screen is landscape. 122 | matrix.setPolyToPoly( 123 | new float[]{ 124 | 0.f, 0.f, // top left 125 | width, 0.f, // top right 126 | 0.f, height, // bottom left 127 | width, height, // bottom right 128 | }, 0, 129 | mDisplayOrientation == 90 ? 130 | // Clockwise 131 | new float[]{ 132 | 0.f, height, // top left 133 | 0.f, 0.f, // top right 134 | width, height, // bottom left 135 | width, 0.f, // bottom right 136 | } : // mDisplayOrientation == 270 137 | // Counter-clockwise 138 | new float[]{ 139 | width, 0.f, // top left 140 | width, height, // top right 141 | 0.f, 0.f, // bottom left 142 | 0.f, height, // bottom right 143 | }, 0, 144 | 4); 145 | } else if (mDisplayOrientation == 180) { 146 | matrix.postRotate(180, getWidth() / 2, getHeight() / 2); 147 | } 148 | mTextureView.setTransform(matrix); 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/AspectRatio.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | import android.os.Parcel; 20 | import android.os.Parcelable; 21 | import android.support.annotation.NonNull; 22 | import android.support.v4.util.SparseArrayCompat; 23 | 24 | /** 25 | * 摄像头的宽高比 26 | * 27 | * Immutable class for describing proportional relationship between width and height. 28 | */ 29 | public class AspectRatio implements Comparable, Parcelable { 30 | 31 | private final static SparseArrayCompat> sCache = new SparseArrayCompat<>(16); 32 | 33 | private final int mX;//宽 34 | private final int mY;//高 35 | 36 | /** 37 | * Returns an instance of {@link AspectRatio} specified by {@code x} and {@code y} values. 38 | * The values {@code x} and {@code} will be reduced by their greatest common divider. 39 | * 40 | * @param x The width 41 | * @param y The height 42 | * @return An instance of {@link AspectRatio} 43 | */ 44 | public static AspectRatio of(int x, int y) { 45 | int gcd = gcd(x, y); 46 | x /= gcd; 47 | y /= gcd; 48 | SparseArrayCompat arrayX = sCache.get(x); 49 | if (arrayX == null) { 50 | AspectRatio ratio = new AspectRatio(x, y); 51 | arrayX = new SparseArrayCompat<>(); 52 | arrayX.put(y, ratio); 53 | sCache.put(x, arrayX); 54 | return ratio; 55 | } else { 56 | AspectRatio ratio = arrayX.get(y); 57 | if (ratio == null) { 58 | ratio = new AspectRatio(x, y); 59 | arrayX.put(y, ratio); 60 | } 61 | return ratio; 62 | } 63 | } 64 | 65 | /** 66 | * Parse an {@link AspectRatio} from a {@link String} formatted like "4:3". 67 | * 68 | * @param s The string representation of the aspect ratio 69 | * @return The aspect ratio 70 | * @throws IllegalArgumentException when the format is incorrect. 71 | */ 72 | public static AspectRatio parse(String s) { 73 | int position = s.indexOf(':'); 74 | if (position == -1) { 75 | throw new IllegalArgumentException("Malformed aspect ratio: " + s); 76 | } 77 | try { 78 | int x = Integer.parseInt(s.substring(0, position)); 79 | int y = Integer.parseInt(s.substring(position + 1)); 80 | return AspectRatio.of(x, y); 81 | } catch (NumberFormatException e) { 82 | throw new IllegalArgumentException("Malformed aspect ratio: " + s, e); 83 | } 84 | } 85 | 86 | private AspectRatio(int x, int y) { 87 | mX = x; 88 | mY = y; 89 | } 90 | 91 | public int getX() { 92 | return mX; 93 | } 94 | 95 | public int getY() { 96 | return mY; 97 | } 98 | 99 | public boolean matches(Size size) { 100 | int gcd = gcd(size.getWidth(), size.getHeight()); 101 | int x = size.getWidth() / gcd; 102 | int y = size.getHeight() / gcd; 103 | return mX == x && mY == y; 104 | } 105 | 106 | @Override 107 | public boolean equals(Object o) { 108 | if (o == null) { 109 | return false; 110 | } 111 | if (this == o) { 112 | return true; 113 | } 114 | if (o instanceof AspectRatio) { 115 | AspectRatio ratio = (AspectRatio) o; 116 | return mX == ratio.mX && mY == ratio.mY; 117 | } 118 | return false; 119 | } 120 | 121 | @Override 122 | public String toString() { 123 | return mX + ":" + mY; 124 | } 125 | 126 | public float toFloat() { 127 | return (float) mX / mY; 128 | } 129 | 130 | @Override 131 | public int hashCode() { 132 | // assuming most sizes are <2^16, doing a rotate will give us perfect hashing 133 | return mY ^ ((mX << (Integer.SIZE / 2)) | (mX >>> (Integer.SIZE / 2))); 134 | } 135 | 136 | @Override 137 | public int compareTo(@NonNull AspectRatio another) { 138 | if (equals(another)) { 139 | return 0; 140 | } else if (toFloat() - another.toFloat() > 0) { 141 | return 1; 142 | } 143 | return -1; 144 | } 145 | 146 | /** 147 | * 4:3的宽高比变成3:4 148 | * 149 | * @return The inverse of this {@link AspectRatio}. 150 | */ 151 | public AspectRatio inverse() { 152 | //noinspection SuspiciousNameCombination 153 | return AspectRatio.of(mY, mX); 154 | } 155 | 156 | private static int gcd(int a, int b) { 157 | while (b != 0) { 158 | int c = b; 159 | b = a % b; 160 | a = c; 161 | } 162 | return a; 163 | } 164 | 165 | @Override 166 | public int describeContents() { 167 | return 0; 168 | } 169 | 170 | @Override 171 | public void writeToParcel(Parcel dest, int flags) { 172 | dest.writeInt(mX); 173 | dest.writeInt(mY); 174 | } 175 | 176 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 177 | 178 | @Override 179 | public AspectRatio createFromParcel(Parcel source) { 180 | int x = source.readInt(); 181 | int y = source.readInt(); 182 | return AspectRatio.of(x, y); 183 | } 184 | 185 | @Override 186 | public AspectRatio[] newArray(int size) { 187 | return new AspectRatio[size]; 188 | } 189 | }; 190 | 191 | } 192 | -------------------------------------------------------------------------------- /library/src/main/base/com/google/android/cameraview/LoggingDelegate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview; 18 | 19 | /** 20 | * Logging interface (参照FB RN源码模式) 21 | * 22 | * Created by javayhu on 8/19/17. 23 | */ 24 | public interface LoggingDelegate { 25 | 26 | /** 27 | * Gets a minimum log-level under which the logger will not log regardless of other checks. 28 | * 29 | * @return the minimum level 30 | */ 31 | int getMinimumLoggingLevel(); 32 | 33 | /** 34 | * Sets a minimum log-level under which the logger will not log regardless of other checks. 35 | * 36 | * @param level the minimum level to set 37 | */ 38 | void setMinimumLoggingLevel(int level); 39 | 40 | /** 41 | * Gets whether the specified level is loggable. 42 | * 43 | * @param level the level to check 44 | * @return the level 45 | */ 46 | boolean isLoggable(int level); 47 | 48 | /** 49 | * Send a {@link android.util.Log#VERBOSE} log message. 50 | * 51 | * @param tag Used to identify the source of a log message. It usually identifies 52 | * the class or activity where the log call occurs. 53 | * @param msg The message you would like logged. 54 | */ 55 | void v(String tag, String msg); 56 | 57 | /** 58 | * Send a {@link android.util.Log#VERBOSE} log message and log the exception. 59 | * 60 | * @param tag Used to identify the source of a log message. It usually identifies 61 | * the class or activity where the log call occurs. 62 | * @param msg The message you would like logged. 63 | * @param tr An exception to log 64 | */ 65 | void v(String tag, String msg, Throwable tr); 66 | 67 | /** 68 | * Send a {@link android.util.Log#DEBUG} log message. 69 | * 70 | * @param tag Used to identify the source of a log message. It usually identifies 71 | * the class or activity where the log call occurs. 72 | * @param msg The message you would like logged. 73 | */ 74 | void d(String tag, String msg); 75 | 76 | /** 77 | * Send a {@link android.util.Log#DEBUG} log message and log the exception. 78 | * 79 | * @param tag Used to identify the source of a log message. It usually identifies 80 | * the class or activity where the log call occurs. 81 | * @param msg The message you would like logged. 82 | * @param tr An exception to log 83 | */ 84 | void d(String tag, String msg, Throwable tr); 85 | 86 | /** 87 | * Send an {@link android.util.Log#INFO} log message. 88 | * 89 | * @param tag Used to identify the source of a log message. It usually identifies 90 | * the class or activity where the log call occurs. 91 | * @param msg The message you would like logged. 92 | */ 93 | void i(String tag, String msg); 94 | 95 | /** 96 | * Send a {@link android.util.Log#INFO} log message and log the exception. 97 | * 98 | * @param tag Used to identify the source of a log message. It usually identifies 99 | * the class or activity where the log call occurs. 100 | * @param msg The message you would like logged. 101 | * @param tr An exception to log 102 | */ 103 | void i(String tag, String msg, Throwable tr); 104 | 105 | /** 106 | * Send a {@link android.util.Log#WARN} log message. 107 | * 108 | * @param tag Used to identify the source of a log message. It usually identifies 109 | * the class or activity where the log call occurs. 110 | * @param msg The message you would like logged. 111 | */ 112 | void w(String tag, String msg); 113 | 114 | /** 115 | * Send a {@link android.util.Log#WARN} log message and log the exception. 116 | * 117 | * @param tag Used to identify the source of a log message. It usually identifies 118 | * the class or activity where the log call occurs. 119 | * @param msg The message you would like logged. 120 | * @param tr An exception to log 121 | */ 122 | void w(String tag, String msg, Throwable tr); 123 | 124 | /** 125 | * Send an {@link android.util.Log#ERROR} log message. 126 | * 127 | * @param tag Used to identify the source of a log message. It usually identifies 128 | * the class or activity where the log call occurs. 129 | * @param msg The message you would like logged. 130 | */ 131 | void e(String tag, String msg); 132 | 133 | /** 134 | * Send a {@link android.util.Log#ERROR} log message and log the exception. 135 | * 136 | * @param tag Used to identify the source of a log message. It usually identifies 137 | * the class or activity where the log call occurs. 138 | * @param msg The message you would like logged. 139 | * @param tr An exception to log 140 | */ 141 | void e(String tag, String msg, Throwable tr); 142 | 143 | /** 144 | * Send an {@link android.util.Log#ERROR} log message. 145 | * Send wtf soft error report (sampled). 146 | * Note: This is not equivalent of {@link android.util.Log#wtf}. 147 | * 148 | * @param tag Used to identify the source of a log message. 149 | * @param msg The message you would like logged. 150 | */ 151 | void wtf(String tag, String msg); 152 | 153 | /** 154 | * Send an {@link android.util.Log#ERROR} log message. 155 | * Send wtf soft error report (sampled). 156 | * Note: This is not equivalent of {@link android.util.Log#wtf}. 157 | * 158 | * @param tag Used to identify the source of a log message. 159 | * @param msg The message you would like logged. 160 | * @param tr An exception to log. May be null. 161 | */ 162 | void wtf(String tag, String msg, Throwable tr); 163 | 164 | /** 165 | * Logs a message. 166 | * 167 | * @param priority the priority of the message 168 | * @param tag Used to identify the source of a log message. 169 | * @param msg The message you would like logged. 170 | */ 171 | void log(int priority, String tag, String msg); 172 | } 173 | -------------------------------------------------------------------------------- /demo/src/main/java/com/google/android/cameraview/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.android.cameraview.demo; 18 | 19 | import android.Manifest; 20 | import android.content.pm.PackageManager; 21 | import android.os.Build; 22 | import android.os.Bundle; 23 | import android.os.Environment; 24 | import android.os.Handler; 25 | import android.os.HandlerThread; 26 | import android.support.annotation.NonNull; 27 | import android.support.design.widget.FloatingActionButton; 28 | import android.support.v4.app.ActivityCompat; 29 | import android.support.v4.app.FragmentManager; 30 | import android.support.v4.content.ContextCompat; 31 | import android.support.v7.app.ActionBar; 32 | import android.support.v7.app.AppCompatActivity; 33 | import android.support.v7.widget.Toolbar; 34 | import android.util.Log; 35 | import android.view.Menu; 36 | import android.view.MenuItem; 37 | import android.view.View; 38 | import android.widget.Toast; 39 | 40 | import com.google.android.cameraview.AspectRatio; 41 | import com.google.android.cameraview.CameraView; 42 | 43 | import java.io.File; 44 | import java.io.FileOutputStream; 45 | import java.io.IOException; 46 | import java.io.OutputStream; 47 | import java.util.Set; 48 | 49 | 50 | /** 51 | * This demo app saves the taken picture to a constant file. 52 | * $ adb pull /sdcard/Android/data/com.google.android.cameraview.demo/files/Pictures/picture.jpg 53 | */ 54 | public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback, AspectRatioFragment.Listener { 55 | 56 | private static final String TAG = "MainActivity"; 57 | 58 | private static final int REQUEST_CAMERA_PERMISSION = 1; 59 | 60 | private static final String FRAGMENT_PERMISSION = "permission"; 61 | private static final String FRAGMENT_PICTURE = "picture"; 62 | 63 | private static final int[] FLASH_OPTIONS = { 64 | CameraView.FLASH_AUTO, 65 | CameraView.FLASH_OFF, 66 | CameraView.FLASH_ON, 67 | }; 68 | 69 | private static final int[] FLASH_ICONS = { 70 | R.drawable.ic_flash_auto, 71 | R.drawable.ic_flash_off, 72 | R.drawable.ic_flash_on, 73 | }; 74 | 75 | private static final int[] FLASH_TITLES = { 76 | R.string.flash_auto, 77 | R.string.flash_off, 78 | R.string.flash_on, 79 | }; 80 | 81 | private int mCurrentFlash; 82 | 83 | private CameraView mCameraView; 84 | 85 | private Handler mBackgroundHandler; 86 | 87 | private View.OnClickListener mOnClickListener = new View.OnClickListener() { 88 | @Override 89 | public void onClick(View v) { 90 | switch (v.getId()) { 91 | case R.id.take_picture: 92 | if (mCameraView != null) { 93 | mCameraView.takePicture(); 94 | } 95 | break; 96 | } 97 | } 98 | }; 99 | 100 | @Override 101 | protected void onCreate(Bundle savedInstanceState) { 102 | super.onCreate(savedInstanceState); 103 | setContentView(R.layout.activity_main); 104 | mCameraView = (CameraView) findViewById(R.id.camera); 105 | if (mCameraView != null) { 106 | mCameraView.addCallback(mCallback); 107 | } 108 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.take_picture); 109 | if (fab != null) { 110 | fab.setOnClickListener(mOnClickListener); 111 | } 112 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 113 | setSupportActionBar(toolbar); 114 | ActionBar actionBar = getSupportActionBar(); 115 | if (actionBar != null) { 116 | actionBar.setDisplayShowTitleEnabled(false); 117 | } 118 | } 119 | 120 | @Override 121 | protected void onResume() { 122 | super.onResume(); 123 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { 124 | try { 125 | mCameraView.start(); 126 | } catch (Exception e) { 127 | Log.e(TAG, "start camera fail", e); 128 | } 129 | } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { 130 | ConfirmationDialogFragment.newInstance(R.string.camera_permission_confirmation, 131 | new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION, R.string.camera_permission_not_granted) 132 | .show(getSupportFragmentManager(), FRAGMENT_PERMISSION); 133 | } else { 134 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); 135 | } 136 | } 137 | 138 | @Override 139 | protected void onPause() { 140 | try { 141 | mCameraView.stop(); 142 | } catch (Exception e) { 143 | Log.e(TAG, "stop camera fail", e); 144 | } 145 | 146 | super.onPause(); 147 | } 148 | 149 | @Override 150 | protected void onDestroy() { 151 | super.onDestroy(); 152 | if (mBackgroundHandler != null) { 153 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 154 | mBackgroundHandler.getLooper().quitSafely(); 155 | } else { 156 | mBackgroundHandler.getLooper().quit(); 157 | } 158 | mBackgroundHandler = null; 159 | } 160 | } 161 | 162 | @Override 163 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 164 | @NonNull int[] grantResults) { 165 | switch (requestCode) { 166 | case REQUEST_CAMERA_PERMISSION: 167 | if (permissions.length != 1 || grantResults.length != 1) { 168 | throw new RuntimeException("Error on requesting camera permission."); 169 | } 170 | if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { 171 | Toast.makeText(this, R.string.camera_permission_not_granted, Toast.LENGTH_SHORT).show(); 172 | } 173 | // No need to start camera here; it is handled by onResume 174 | break; 175 | } 176 | } 177 | 178 | @Override 179 | public boolean onCreateOptionsMenu(Menu menu) { 180 | getMenuInflater().inflate(R.menu.main, menu); 181 | return true; 182 | } 183 | 184 | @Override 185 | public boolean onOptionsItemSelected(MenuItem item) { 186 | switch (item.getItemId()) { 187 | case R.id.aspect_ratio: 188 | FragmentManager fragmentManager = getSupportFragmentManager(); 189 | if (mCameraView != null && fragmentManager.findFragmentByTag(FRAGMENT_PERMISSION) == null) { 190 | final Set ratios = mCameraView.getSupportedAspectRatios(); 191 | final AspectRatio currentRatio = mCameraView.getAspectRatio(); 192 | AspectRatioFragment.newInstance(ratios, currentRatio).show(fragmentManager, 193 | FRAGMENT_PERMISSION); 194 | } 195 | return true; 196 | case R.id.switch_flash: 197 | if (mCameraView != null) { 198 | mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length; 199 | item.setTitle(FLASH_TITLES[mCurrentFlash]); 200 | item.setIcon(FLASH_ICONS[mCurrentFlash]); 201 | mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]); 202 | } 203 | return true; 204 | case R.id.switch_camera: 205 | if (mCameraView != null) { 206 | int facing = mCameraView.getFacing(); 207 | mCameraView.setFacing(facing == CameraView.FACING_FRONT ? CameraView.FACING_BACK : CameraView.FACING_FRONT); 208 | } 209 | return true; 210 | } 211 | return super.onOptionsItemSelected(item); 212 | } 213 | 214 | @Override 215 | public void onAspectRatioSelected(@NonNull AspectRatio ratio) { 216 | if (mCameraView != null) { 217 | Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show(); 218 | mCameraView.setAspectRatio(ratio); 219 | } 220 | } 221 | 222 | private Handler getBackgroundHandler() { 223 | if (mBackgroundHandler == null) { 224 | HandlerThread thread = new HandlerThread("background"); 225 | thread.start(); 226 | mBackgroundHandler = new Handler(thread.getLooper()); 227 | } 228 | return mBackgroundHandler; 229 | } 230 | 231 | private CameraView.Callback mCallback = new CameraView.Callback() { 232 | 233 | @Override 234 | public void onCameraError(CameraView cameraView) { 235 | Log.e(TAG, "onCameraError"); 236 | } 237 | 238 | @Override 239 | public void onCameraOpened(CameraView cameraView) { 240 | Log.d(TAG, "onCameraOpened"); 241 | } 242 | 243 | @Override 244 | public void onCameraClosed(CameraView cameraView) { 245 | Log.d(TAG, "onCameraClosed"); 246 | } 247 | 248 | @Override 249 | public void onPictureTaken(CameraView cameraView, final byte[] data) { 250 | Log.d(TAG, "onPictureTaken " + data.length); 251 | Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT).show(); 252 | getBackgroundHandler().post(new Runnable() { 253 | @Override 254 | public void run() { 255 | long time = System.currentTimeMillis(); 256 | File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), String.format("picture_%s.jpg", String.valueOf(time))); 257 | OutputStream os = null; 258 | try { 259 | os = new FileOutputStream(file); 260 | os.write(data); 261 | os.close(); 262 | 263 | PictureDialogFragment.newInstance(file.getAbsolutePath()).show(getSupportFragmentManager(), FRAGMENT_PICTURE); 264 | } catch (IOException e) { 265 | Log.w(TAG, "Cannot write to " + file, e); 266 | } finally { 267 | if (os != null) { 268 | try { 269 | os.close(); 270 | } catch (IOException e) { 271 | // Ignore 272 | } 273 | } 274 | } 275 | } 276 | }); 277 | } 278 | 279 | }; 280 | 281 | } 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

168 | 169 | 170 | 171 | xmlns:android 172 | ^$ 173 | 174 | 175 | 176 |
177 |
178 | 179 | 180 | 181 | xmlns:.* 182 | ^$ 183 | 184 | 185 | BY_NAME 186 | 187 |
188 |
189 | 190 | 191 | 192 | .*:id 193 | http://schemas.android.com/apk/res/android 194 | 195 | 196 | 197 |
198 |
199 | 200 | 201 | 202 | .*:name 203 | http://schemas.android.com/apk/res/android 204 | 205 | 206 | 207 |
208 |
209 | 210 | 211 | 212 | name 213 | ^$ 214 | 215 | 216 | 217 |
218 |
219 | 220 | 221 | 222 | style 223 | ^$ 224 | 225 | 226 | 227 |
228 |
229 | 230 | 231 | 232 | .* 233 | ^$ 234 | 235 | 236 | BY_NAME 237 | 238 |
239 |
240 | 241 | 242 | 243 | .*:layout_width 244 | http://schemas.android.com/apk/res/android 245 | 246 | 247 | 248 |
249 |
250 | 251 | 252 | 253 | .*:layout_height 254 | http://schemas.android.com/apk/res/android 255 | 256 | 257 | 258 |
259 |
260 | 261 | 262 | 263 | .*:layout_.* 264 | http://schemas.android.com/apk/res/android 265 | 266 | 267 | BY_NAME 268 | 269 |
270 |
271 | 272 | 273 | 274 | .*:width 275 | http://schemas.android.com/apk/res/android 276 | 277 | 278 | BY_NAME 279 | 280 |
281 |
282 | 283 | 284 | 285 | .*:height 286 | http://schemas.android.com/apk/res/android 287 | 288 | 289 | BY_NAME 290 | 291 |
292 |
293 | 294 | 295 | 296 | .* 297 | http://schemas.android.com/apk/res/android 298 | 299 | 300 | BY_NAME 301 | 302 |
303 |
304 | 305 | 306 | 307 | .* 308 | .* 309 | 310 | 311 | BY_NAME 312 | 313 |
314 | 315 | 316 | 317 | 318 | 319 |