android 切换摄像头加动画,android前后摄像头切换
android前后摄像头切换demo,startview后的页面上有切换、拍照两个按钮,拍照后照片未保存,需要保存的请看下方注释,实现了拍照、聚焦功能,以下是CameraPreview.java源码:
package com.myselftest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import android.widget.RelativeLayout;
import android.view.MotionEvent;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.hardware.Camera.CameraInfo;
import android.os.SystemProperties;
import android.view.View.OnTouchListener;
import android.graphics.Rect;
import android.hardware.Camera.PictureCallback;
public class CameraPreview extends Activity implements OnClickListener, SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private Camera mCamera;
private Camera.Parameters mCameraParam;
private int mPrvW = 800;
private int mPrvH = 600;
private final AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback();
private long mFocusCallbackTime;
private FocusIndicatorView mFocusIndicatorView;
private static final int WIDTH_DP = 80;
private static final int HEIGTH_DP = 80;
private boolean focusing = false;
private boolean state;
private TextView btn_position = null;
private TextView btn_capture = null;
private SurfaceHolder holder = null;
private VideoPreview mVideoPreview;
private int cameraPosition = 1; //1,camera_back 0,camera_front
private int cameraId;
private RelativeLayout mRelativeLayout;
CameraInfo ci = null;
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
btn_position = (TextView) findViewById(R.id.btn_position);
btn_capture = (TextView) findViewById(R.id.btn_capture);
mPrvW = this.getWindow().getWindowManager().getDefaultDisplay().getWidth();
mPrvH = mPrvW*4/3;
mFocusIndicatorView = new FocusIndicatorView(this);
int width_px = dip2px(this, WIDTH_DP);
int heigth_px = dip2px(this, HEIGTH_DP);
RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(width_px, heigth_px);
int[] rules = mLayoutParams.getRules();
rules[RelativeLayout.CENTER_IN_PARENT] = 1;
mRelativeLayout = (RelativeLayout) findViewById(R.id.main_layout);
mRelativeLayout.addView(mFocusIndicatorView, mLayoutParams);
mRelativeLayout.setOnTouchListener(onTouchListener);
mVideoPreview = (VideoPreview) findViewById(R.id.camera_preview);
btn_position.setOnClickListener(this);
btn_capture.setOnClickListener(this);
}
@Override
public void onClick(View v){
if(v.equals(btn_position)){
camera_position();
}else if(v.equals(btn_capture)){
rawCapture();
}
}
@Override
protected void onResume() {
super.onResume();
mVideoPreview.setAspectRatio(mPrvW, mPrvH);
holder = mVideoPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public boolean onTouchEvent(MotionEvent event) {
if(focusing == false) {
focusing = true;
mFocusIndicatorView.showStart();
mCamera.autoFocus(mAutoFocusCallback);
}
return true;
}
public class FocusIndicatorView extends View {
public FocusIndicatorView(Context context) {
super(context);
}
private void setDrawable(int resid) {
setBackgroundDrawable(getResources().getDrawable(resid));
}
public void showStart() {
setDrawable(R.drawable.ic_focus_focusing);
}
public void showSuccess() {
setDrawable(R.drawable.ic_focus_focused);
}
public void showFail() {
setDrawable(R.drawable.ic_focus_failed);
}
public void clear() {
setBackgroundDrawable(null);
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged width is : " + width+" height is"+height+" ci.orientation="+ci.orientation);
startPreview(ci.orientation);
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
ci = new CameraInfo();
Camera.getCameraInfo(0, ci);
openCamera(0);
cameraId = 0;
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
closeCamera();
Log.i(TAG, "surfaceCreated closeCamera ");
}
}
private void openCamera(int cmaId) {
if (mCamera == null) {
mCamera = Camera.open(cmaId);
cameraId = cmaId;
Log.i(TAG, "Enter openCamera to init the mCamera.");
if (null == mCamera) {
Log.i(TAG, "init the mCamera is null.");
}
}
}
private void closeCamera() {
if (null != mCamera) {
mCamera.release();
mCamera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
stopPreview();
closeCamera();
Log.i(TAG, "surfaceDestroyed closeCamera ");
}
private void stopPreview() {
if (null != mCamera) {
mCamera.stopPreview();
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (0 == msg.what) {
mFocusIndicatorView.clear();
}
}
};
private void startPreview(int orientation) {//orientation:当前所选摄像头的偏转角度
if (null != mCamera) {
mCameraParam = mCamera.getParameters();
}else{
return;
}
Size size = mCameraParam.getPictureSize();
List sizes = mCameraParam.getSupportedPreviewSizes();
Size optimalSize = null;
if (size != null && size.height != 0) {
optimalSize = getOptimalPreviewSize(sizes, (double) mPrvH / mPrvW);
}
if (optimalSize != null) {
mCameraParam.setPreviewSize(optimalSize.width, optimalSize.height);
} else {
mCameraParam.setPreviewSize(mPrvW, mPrvH);
}
mCameraParam.set("fps-mode", 0); // Frame rate is normal
mCameraParam.set("cam-mode", 0); // Cam mode is preview
if (cameraPosition == 1) {
mCameraParam.setFocusMode(mCameraParam.FOCUS_MODE_CONTINUOUS_PICTURE);
mCameraParam.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
}
mCamera.setDisplayOrientation(orientation);
mCamera.setParameters(mCameraParam);
mCamera.startPreview();
mCamera.autoFocus(mAutoFocusCallback);
}
private Size getOptimalPreviewSize(List sizes, double targetRatio) {
final double ASPECT_TOLERANCE = 0.05;
if (sizes == null) {
return null;
}
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
Display display = getWindowManager().getDefaultDisplay();
int targetHeight = Math.min(display.getHeight(), display.getWidth());
if (targetHeight <= 0) {
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
targetHeight = windowManager.getDefaultDisplay().getHeight();
}
Log.d(TAG, "getOptimalPreviewSize() sizes.size = " + sizes.size());
int i = 1;
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
i++;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
continue;
}
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
Log.d(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
} else {
Log.d(TAG, String.format("Optimal preview size is %sx%s", optimalSize.width, optimalSize.height));
}
return optimalSize;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
return true;
case KeyEvent.KEYCODE_SEARCH:
return true;
case KeyEvent.KEYCODE_FOCUS:
return true;
case KeyEvent.KEYCODE_BACK:
break;
}
return super.onKeyDown(keyCode, event);
}
private void camera_position(){
CameraInfo cameraInfo = new CameraInfo();
int cameraCount = Camera.getNumberOfCameras();
for(int i = 0; i
Camera.getCameraInfo(i, cameraInfo);
Log.d(TAG, "cameraOrientation-"+i+":"+cameraInfo.orientation);
if(cameraPosition == 0){
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK){
stopPreview();
closeCamera();
openCamera(i);
cameraPosition = 1;
if (null != mCamera) {
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException ex) {
closeCamera();
Log.i(TAG, "camera_position closeCamera "+i);
ex.printStackTrace();
}
startPreview(cameraInfo.orientation);
}
break;
}
}else{
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
stopPreview();
closeCamera();
openCamera(i);
cameraPosition = 0;
if (null != mCamera) {
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException ex) {
closeCamera();
Log.i(TAG, "camera_position closeCamera "+i);
ex.printStackTrace();
}
startPreview(90);
}
break;
}
}
}
}
private void rawCapture() {
if(mCamera != null){
try {
mCamera.startPreview();
mCamera.autoFocus(mAutoFocusCallback);
mCamera.takePicture(null, null, new JpegPictureCallback());
Toast.makeText(this, getString(R.string.cma_capture_success), Toast.LENGTH_LONG).show();
mCamera.stopPreview();
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(Exception ex){
closeCamera();
ex.printStackTrace();
}
Log.i(TAG, "rawCapture function end");
}
}
private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback {
public void onAutoFocus(boolean focused, android.hardware.Camera camera) {
mFocusCallbackTime = System.currentTimeMillis();
Log.i(TAG, "mFocusCallbackTime is " + mFocusCallbackTime);
if(focused && !state) {
mFocusIndicatorView.showSuccess();
mHandler.sendEmptyMessageDelayed(0, 1500);
} else if(!focused){
mHandler.removeMessages(0);
mFocusIndicatorView.showFail();
}
focusing = false;
state = focused;
}
}
private final class JpegPictureCallback implements PictureCallback {
public void onPictureTaken(byte[] jpegData, android.hardware.Camera camera) {
Log.d(TAG, "mJpegPictureCallbackTime = " + System.currentTimeMillis());
if (jpegData != null) {
storeImage(jpegData);
}
}
}
private void storeImage(byte[] jpegData) {//本例未保存所拍照片,如需要保存,请取消下方的注释
String name = "factorymode_test.jpg";
// File fHandle = new File(name);
// try {
// OutputStream bos = new FileOutputStream(fHandle);
// bos.write(jpegData);
// bos.close();
// long storeImageTime = System.currentTimeMillis();
// Log.d(TAG, "storeImageTime = " + storeImageTime);
// } catch (Exception ex) {
// fHandle.delete();
// }
}
OnTouchListener onTouchListener = new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){
mFocusIndicatorView.setX(event.getX());
mFocusIndicatorView.setY(event.getY());
if(event.getAction() == MotionEvent.ACTION_DOWN){
mFocusIndicatorView.showSuccess();
}else if(event.getAction() == MotionEvent.ACTION_UP){
mFocusIndicatorView.showFail();
if(cameraPosition == 1){
focusOnTouch(event);
}
}
return true;
}
};
private void focusOnTouch(MotionEvent event){
int [] location = new int[2];
mRelativeLayout.getLocationOnScreen(location);
Rect focusRect = calculateTapArea(mVideoPreview.getWidth(), mVideoPreview.getHeight(), 1f, event.getRawX(),
event.getRawY(), location[0], location[0] + mRelativeLayout.getWidth(), location[1], location[1] + mRelativeLayout.getHeight());
Rect meteringRect = calculateTapArea(mVideoPreview.getWidth(), mVideoPreview.getHeight(), 1.5f, event.getRawX(),
event.getRawY(), location[0], location[0] + mRelativeLayout.getWidth(), location[1], location[1] + mRelativeLayout.getHeight());
mCameraParam.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if(mCameraParam.getMaxNumFocusAreas() > 0){
List focusAreas = new ArrayList();
focusAreas.add(new Camera.Area(focusRect, 1000));
mCameraParam.setFocusAreas(focusAreas);
}
if(mCameraParam.getMaxNumMeteringAreas() > 0){
List meteringAreas = new ArrayList();
meteringAreas.add(new Camera.Area(meteringRect, 1000));
mCameraParam.setMeteringAreas(meteringAreas);
}
if(mCamera != null){
mCamera.setParameters(mCameraParam);
}
mCamera.autoFocus(mAutoFocusCallback);
}
private Rect calculateTapArea(int focusWidth, int focusHeight, float areaMultiple, float x, float y, int previewLeft, int previewRight, int preViewTop, int preViewBottom){
int areaWidth = (int)(focusWidth * areaMultiple);
int areaHeight = (int)(focusHeight * areaMultiple);
int centerX = (previewLeft + previewRight) / 2;
int centerY = (preViewTop + preViewBottom) / 2;
double unitx = (((double)previewRight - (double)previewLeft)) /2000;
double unity = (((double)preViewBottom - (double)preViewTop)) /2000;
int left = clamp((int)(((x - areaWidth / 2) - centerX) / unitx), -1000, 1000);
int top = clamp((int)(((y - areaHeight / 2) - centerY) / unity), -1000, 1000);
int right = clamp((int)(left + areaWidth / unitx), -1000, 1000);
int bottom = clamp((int)(top + areaHeight / unity), -1000, 1000);
return new Rect(left, top, right, bottom);
}
private int clamp(int x, int min, int max){
if(x > max){
return max;
}
if(x < min){
return min;
}
return x;
}
}
camera_preview.xml布局文件:
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/main_layout"
android:orientation="vertical">
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"/>
android:id="@+id/btn_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="33dp"
android:gravity="center"
android:text="@string/cma_capture" />
android:id="@+id/btn_position"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="48dp"
android:gravity="center"
android:text="@string/cma_position" />
以上代码在android6.0上测试通过。
android 切换摄像头加动画,android前后摄像头切换相关推荐
- android 向左滑动动画,Android Activity左边滑出,右边滑入的动画切换
Activity的切换动画实际上是Android的View Animation(视图动画)中的Tween Animation效果,Tween Animation分为4种动画效果,分别是:alpha ( ...
- android跳转界面动画,Android Activity跳转动画效果
Activity的跳转动画在5.0的时候做了一个重大的突破,下面来看一下吧 1.5.0之前的overridePendingTransition 相信大家对OverridePendingTransiti ...
- android夜间模式揭露动画,Android Material Design系列之夜间模式
今天我们讲讲夜间模式的实现,这篇文章的名字应该叫:<Android Material Design系列之夜间模式>.在Android 5.0 之后,实现夜间模式并非很难了,支持的5.0库提 ...
- android 图片预览动画,Android实现仿Windows7图片预览窗格效果
本实例将显示类似于windows7提供的图片预览窗格效果,单击任意一张图片,可以在右侧显示该图片的预览效果. 效果如图所示: 具体实现方法: res/layout/main.xml: android: ...
- Android仿新浪微博弹出界面动画,Android仿新浪微博启动界面或登陆界面(1)
本文为大家分享了Android模仿新浪微博启动界面&登陆界面的具体实现代码,供大家参考,具体内容如下 启动界面 主要有两个功能: 1.加载启动动画 2.判断网络,有者直接进入登陆界面,否则去设 ...
- android 张口逐帧动画,Android中实现一个简单的逐帧动画(附代码下载)
场景 Android中的逐帧动画,就是由连续的一张张照片组成的动画. 效果 注: 实现 首先准备一组不同表情的照片,放在res/drawable下,然后在此目录下新建动画资源文件fairy.xml 这 ...
- android 向左滑动动画,Android中的滑动动画
这是问题所在. 我想从左到右滑动(在下面的代码中从右到左--) 所以请帮我动画(XML动画与此相反)-- (当前任务在按钮单击时正确运行-) 这是源- public class MainActivit ...
- android imageview图片旋转动画,Android 安卓动画 属性动画 - 旋转动画
引入 属性动画的出现,弥补了补间动画的不足之处,补间动画,只是改变了表面上的东西,但是其中属性并未改变,而属性动画相反,改变了表面上的东西,并且也更改了其属性. 类:ObjectAnimator 用于 ...
- android自定义图片加载,Android自定义ProgressDialog加载图片
为了提高用户体验,我们肯定希望该Dialog能更加炫酷,让用户看着更舒服.那如何做呢,当然是我们自己定义一个ProgressDialog了. 一.使用系统加载框 mDialog = new Progr ...
最新文章
- 牛客 - Subset of Five(背包)
- php在数据流(内存)中操纵远程数据
- java createcriteria_Hibernate createCriteria查询详解
- uuid和自增_mysql表用自增id还是uuid
- linux command read the content,Linux while 和 read 的用法
- spring 如何决定使用jdk动态代理和cglib(转)
- 云原生日志管理瑞士军刀 Fluent Operator 中文入门教程
- windows虚拟显示器开发(二)WDDM hook(USB转HDMI驱动、USB手写屏开发)
- WordPress小程序源码 社区论坛小程序源码 知识付费商城小程序下载
- Cross-Modal Weighting Network for RGB-D Salient Object Detection
- Windows 10 20H1 2004新功能
- erp打印面单 php实现,利用店小秘ERP处理Shopee虾皮订单及打印面单
- 浅谈华为如何实现区块链的安全隐私保护
- 与西安协同销售总监赵建春先生避风塘聊天记
- [leetcode数据库13] 1873. Calculate Special Bonus
- 伪随机函数 密码学_密码学与理论2:什么是伪随机
- 目标检测数据集:坦克(2)
- php足疗预约,足浴养生管理系统轻松实现各种线上预约功能?
- 什么是8K视频技术!8K视频测试解决方案
- [32位汇编系列]004 - 对话框资源的使用(2)
热门文章
- Js实现获取当前时间并显示
- 编译原理-第一章-引论
- 2.11 header footer hgroup address元素
- JavaScript11:事件
- Camtasia Studio 6录制视频时鼠标闪烁的解决办法
- Windows微信文本压缩算法分析
- Python+OpenCV实用案例应用教程:基于OpenCV的图像处理
- stm32十六进制字符串转十进制数值代码
- 【开源WebGIS】07-Openlayers+Vue 测量功能-02
- c语言实现1024点fft程序,数字信号处理的步骤与注意事项,并编写1024个采样点的FFT C语言程序...