源码:http://files.cnblogs.com/android100/StandardCamera2013-10-18.zip

废话不说了,就是加个seekbar,拖动的话能够调节焦距,让画面变大或缩小。下面是核心程序:

一,camera的布局文件

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:text="@string/BestWish"
  10. tools:context=".StandardCamera" />
  11. <RelativeLayout
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content" >
  14. <FrameLayout
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content" >
  17. <SurfaceView
  18. android:id="@+id/previewSV"
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content" />
  21. </FrameLayout>
  22. <LinearLayout
  23. android:id="@+id/zoomLayout"
  24. android:layout_width="wrap_content"
  25. android:layout_height="40dp"
  26. android:layout_centerInParent="true"
  27. android:layout_centerHorizontal="true"
  28. android:orientation="horizontal" >
  29. <TextView
  30. android:id="@+id/textView1"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:text="-"
  34. android:textColor="#ffffff"
  35. android:textSize="30dip"/>
  36. <SeekBar
  37. android:id="@+id/seekbar_zoom"
  38. android:layout_width="300dp"
  39. android:layout_height="wrap_content"
  40. android:layout_gravity="center_vertical"
  41. android:progressDrawable="@drawable/seekbar_style"
  42. android:thumb="@drawable/ic_launcher"
  43. android:thumbOffset="0dp" />
  44. <TextView
  45. android:id="@+id/textView2"
  46. android:layout_width="wrap_content"
  47. android:layout_height="wrap_content"
  48. android:text="+"
  49. android:textColor="#ffffff"
  50. android:textSize="30dip" />
  51. </LinearLayout>
  52. </RelativeLayout>
  53. <ImageButton
  54. android:id="@+id/photoImgBtn"
  55. android:layout_width="wrap_content"
  56. android:layout_height="wrap_content"
  57. android:layout_gravity="center"
  58. android:background="@drawable/photo_img_btn" />
  59. </LinearLayout>

其中里面嵌套的LinearLayout就是那个ZoomBar,最外面我用了相对布局,发现相对布局用起来还是很好用的。为了方便以后扩展,Camera的SurfaceView用的帧布局。注意SeekBar的几个参数,其中的progressDrawable是指那个横条的形状,可以直接用个图片,也可以写个xml文件。这里用的是xml,当然用图片很简单。seekbar_style.xml文件如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  3. <item android:id="@android:id/background">
  4. <shape>
  5. <corners android:radius="5dip" />
  6. <gradient
  7. android:startColor="#ff9d9e9d"
  8. android:centerColor="#ff5a5d5a"
  9. android:centerY="0.75"
  10. android:endColor="#ff747674"
  11. android:angle="270"
  12. />
  13. </shape>
  14. </item>
  15. </layer-list>

下面的android:thumb是滑动的那个手柄,本来我是写了一个xml文件,名字为thumb.xml如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <!-- 按下状态 -->
  4. <item android:state_focused="true" android:state_pressed="true"><shape android:shape="oval">
  5. <gradient android:angle="0" android:centerColor="#FF00FF00" android:endColor="#000000" android:gradientRadius="8" android:startColor="#FFFF0000" android:type="radial" />
  6. <size android:height="20dip" android:width="20dip"></size>
  7. </shape></item>
  8. </selector>

无奈啥也显示不出来,索性直接找了个粗糙的图片,见谅哈!

二,整个程序的主代码:

  1. package yan.guoqi.camera;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.util.List;
  7. import yan.guoqi.rectphoto.R;
  8. import android.app.Activity;
  9. import android.content.Context;
  10. import android.graphics.Bitmap;
  11. import android.graphics.BitmapFactory;
  12. import android.graphics.ColorMatrixColorFilter;
  13. import android.graphics.Matrix;
  14. import android.graphics.PixelFormat;
  15. import android.hardware.Camera;
  16. import android.hardware.Camera.AutoFocusCallback;
  17. import android.hardware.Camera.Parameters;
  18. import android.hardware.Camera.PictureCallback;
  19. import android.hardware.Camera.PreviewCallback;
  20. import android.hardware.Camera.ShutterCallback;
  21. import android.os.Bundle;
  22. import android.util.Log;
  23. import android.view.Display;
  24. import android.view.MotionEvent;
  25. import android.view.SurfaceHolder;
  26. import android.view.SurfaceView;
  27. import android.view.View;
  28. import android.view.View.OnClickListener;
  29. import android.view.View.OnTouchListener;
  30. import android.view.ViewGroup.LayoutParams;
  31. import android.view.Window;
  32. import android.view.WindowManager;
  33. import android.widget.ImageButton;
  34. import android.widget.SeekBar;
  35. import android.widget.SeekBar.OnSeekBarChangeListener;
  36. public class StandardCamera extends Activity implements SurfaceHolder.Callback, PreviewCallback{
  37. private static final String tag="StandardCamera";
  38. private boolean isPreview = false;
  39. private SurfaceView mPreviewSV = null; //棰勮SurfaceView
  40. private SurfaceHolder mySurfaceHolder = null;
  41. private ImageButton mPhotoImgBtn = null;
  42. private Camera myCamera = null;
  43. private Bitmap mBitmap = null;
  44. private AutoFocusCallback myAutoFocusCallback = null;
  45. boolean flag = true;
  46. private SeekBar mZoomBar = null;
  47. @Override
  48. public void onCreate(Bundle savedInstanceState) {
  49. super.onCreate(savedInstanceState);
  50. requestWindowFeature(Window.FEATURE_NO_TITLE);
  51. int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
  52. Window myWindow = this.getWindow();
  53. myWindow.setFlags(flag, flag);
  54. setContentView(R.layout.activity_rect_photo);
  55. initView();
  56. mySurfaceHolder = mPreviewSV.getHolder();
  57. mySurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
  58. mySurfaceHolder.addCallback(this);
  59. mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  60. myAutoFocusCallback = new AutoFocusCallback() {
  61. public void onAutoFocus(boolean success, Camera camera) {
  62. // TODO Auto-generated method stub
  63. if(success)
  64. {
  65. Log.i(tag, "myAutoFocusCallback: success...");
  66. }
  67. else
  68. {
  69. Log.i(tag, "myAutoFocusCallback: 澶辫触浜�?.");
  70. }
  71. }
  72. };
  73. //添加ZoomBar
  74. mZoomBar = (SeekBar)findViewById(R.id.seekbar_zoom);
  75. mZoomBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
  76. public void onStopTrackingTouch(SeekBar seekBar) {
  77. // TODO Auto-generated method stub
  78. }
  79. public void onStartTrackingTouch(SeekBar seekBar) {
  80. // TODO Auto-generated method stub
  81. }
  82. public void onProgressChanged(SeekBar seekBar, int progress,
  83. boolean fromUser) {
  84. // TODO Auto-generated method stub
  85. Parameters p = myCamera.getParameters();
  86. p.setZoom(progress);
  87. myCamera.setParameters(p);
  88. }
  89. });
  90. }
  91. public void initView(){
  92. mPreviewSV = (SurfaceView)findViewById(R.id.previewSV);
  93. WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
  94. Display display = wm.getDefaultDisplay();
  95. LayoutParams lpSV = mPreviewSV.getLayoutParams();
  96. lpSV.width = display.getWidth();
  97. lpSV.height = (int) ((float)display.getHeight()*0.75);
  98. mPreviewSV.setLayoutParams(lpSV);
  99. mPhotoImgBtn = (ImageButton)findViewById(R.id.photoImgBtn);
  100. LayoutParams lp = mPhotoImgBtn.getLayoutParams();
  101. lp.width = 240;
  102. lp.height = 240;
  103. mPhotoImgBtn.setLayoutParams(lp);
  104. mPhotoImgBtn.setOnClickListener(new PhotoOnClickListener());
  105. mPhotoImgBtn.setOnTouchListener(new MyOnTouchListener());
  106. }
  107. public void surfaceChanged(SurfaceHolder holder, int format, int width,int height)
  108. {
  109. // TODO Auto-generated method stub
  110. Log.i(tag, "SurfaceHolder.Callback:surfaceChanged!");
  111. initCamera();
  112. }
  113. public void surfaceCreated(SurfaceHolder holder)
  114. {
  115. // TODO Auto-generated method stub
  116. myCamera = Camera.open();
  117. try {
  118. myCamera.setPreviewDisplay(mySurfaceHolder);
  119. Log.i(tag, "SurfaceHolder.Callback: surfaceCreated!");
  120. } catch (IOException e) {
  121. // TODO Auto-generated catch block
  122. if(null != myCamera){
  123. myCamera.release();
  124. myCamera = null;
  125. }
  126. e.printStackTrace();
  127. }
  128. }
  129. public void surfaceDestroyed(SurfaceHolder holder)
  130. {
  131. // TODO Auto-generated method stub
  132. Log.i(tag, "SurfaceHolder.Callback锛歋urface Destroyed");
  133. if(null != myCamera)
  134. {
  135. myCamera.setPreviewCallback(null);
  136. myCamera.stopPreview();
  137. isPreview = false;
  138. myCamera.release();
  139. myCamera = null;
  140. }
  141. }
  142. public void initCamera(){
  143. if(isPreview){
  144. myCamera.stopPreview();
  145. }
  146. if(null != myCamera){
  147. Camera.Parameters myParam = myCamera.getParameters();
  148. myParam.setPictureFormat(PixelFormat.JPEG);//璁剧疆鎷嶇収鍚庡瓨鍌ㄧ殑鍥剧墖鏍煎紡
  149. //List<Size> pictureSizes = myParam.getSupportedPictureSizes();
  150. //List<Size> previewSizes = myParam.getSupportedPreviewSizes();
  151. //          for(int i=0; i<pictureSizes.size(); i++){
  152. //              Size size = pictureSizes.get(i);
  153. //              Log.i(tag, "initCamera:pictureSizes: width = "+size.width+"height = "+size.height);
  154. //          }
  155. //          for(int i=0; i<previewSizes.size(); i++){
  156. //              Size size = previewSizes.get(i);
  157. //              Log.i(tag, "initCamera:鎽勫儚澶存敮鎸佺殑previewSizes: width = "+size.width+"height = "+size.height);
  158. //
  159. //          }
  160. myParam.setPictureSize(1280, 960);  //
  161. myParam.setPreviewSize(960, 720);   //
  162. //myParam.set("rotation", 90);
  163. myCamera.setDisplayOrientation(90);
  164. List<String> focuseMode = (myParam.getSupportedFocusModes());
  165. for(int i=0; i<focuseMode.size(); i++){
  166. Log.i(tag, focuseMode.get(i));
  167. if(focuseMode.get(i).contains("continuous")){
  168. myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
  169. }
  170. else{
  171. myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
  172. }
  173. }
  174. //设置mZoomBar的最大值
  175. mZoomBar.setMax(myParam.getMaxZoom());
  176. myCamera.setParameters(myParam);
  177. myCamera.startPreview();
  178. myCamera.autoFocus(myAutoFocusCallback);
  179. isPreview = true;
  180. }
  181. }
  182. ShutterCallback myShutterCallback = new ShutterCallback()
  183. {
  184. public void onShutter() {
  185. // TODO Auto-generated method stub
  186. Log.i(tag, "myShutterCallback:onShutter...");
  187. }
  188. };
  189. PictureCallback myRawCallback = new PictureCallback()
  190. {
  191. public void onPictureTaken(byte[] data, Camera camera) {
  192. // TODO Auto-generated method stub
  193. Log.i(tag, "myRawCallback:onPictureTaken...");
  194. }
  195. };
  196. PictureCallback myJpegCallback = new PictureCallback()
  197. {
  198. public void onPictureTaken(byte[] data, Camera camera) {
  199. // TODO Auto-generated method stub
  200. Log.i(tag, "myJpegCallback:onPictureTaken...");
  201. if(null != data){
  202. mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//data鏄瓧鑺傛暟鎹紝灏嗗叾瑙f瀽鎴愪綅鍥�                myCamera.stopPreview();
  203. isPreview = false;
  204. }
  205. Matrix matrix = new Matrix();
  206. matrix.postRotate((float)90.0);
  207. Bitmap rotaBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, false);
  208. if(null != rotaBitmap)
  209. {
  210. saveJpeg(rotaBitmap);
  211. }
  212. myCamera.startPreview();
  213. isPreview = true;
  214. }
  215. };
  216. public class PhotoOnClickListener implements OnClickListener{
  217. public void onClick(View v) {
  218. // TODO Auto-generated method stub
  219. if(isPreview && myCamera!=null){
  220. myCamera.takePicture(myShutterCallback, null, myJpegCallback);
  221. }
  222. }
  223. }
  224. public void saveJpeg(Bitmap bm){
  225. String savePath = "/mnt/sdcard/rectPhoto/";
  226. File folder = new File(savePath);
  227. if(!folder.exists()) {
  228. folder.mkdir();
  229. }
  230. long dataTake = System.currentTimeMillis();
  231. String jpegName = savePath + dataTake +".jpg";
  232. Log.i(tag, "saveJpeg:jpegName--" + jpegName);
  233. //File jpegFile = new File(jpegName);
  234. try {
  235. FileOutputStream fout = new FileOutputStream(jpegName);
  236. BufferedOutputStream bos = new BufferedOutputStream(fout);
  237. //          Bitmap newBM = bm.createScaledBitmap(bm, 600, 800, false);
  238. bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
  239. bos.flush();
  240. bos.close();
  241. } catch (IOException e) {
  242. // TODO Auto-generated catch block
  243. e.printStackTrace();
  244. }
  245. }
  246. public class MyOnTouchListener implements OnTouchListener{
  247. public final  float[] BT_SELECTED=new float[]
  248. { 2, 0, 0, 0, 2,
  249. 0, 2, 0, 0, 2,
  250. 0, 0, 2, 0, 2,
  251. 0, 0, 0, 1, 0 };
  252. public final float[] BT_NOT_SELECTED=new float[]
  253. { 1, 0, 0, 0, 0,
  254. 0, 1, 0, 0, 0,
  255. 0, 0, 1, 0, 0,
  256. 0, 0, 0, 1, 0 };
  257. public boolean onTouch(View v, MotionEvent event) {
  258. // TODO Auto-generated method stub
  259. if(event.getAction() == MotionEvent.ACTION_DOWN){
  260. v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
  261. v.setBackgroundDrawable(v.getBackground());
  262. }
  263. else if(event.getAction() == MotionEvent.ACTION_UP){
  264. v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
  265. v.setBackgroundDrawable(v.getBackground());
  266. }
  267. return false;
  268. }
  269. }
  270. @Override
  271. public void onBackPressed()
  272. {
  273. // TODO Auto-generated method stub
  274. super.onBackPressed();
  275. StandardCamera.this.finish();
  276. }
  277. class UpdateThread implements Runnable{
  278. public void run() {
  279. // TODO Auto-generated method stub
  280. while(flag){
  281. if(myCamera!=null && isPreview)
  282. myCamera.autoFocus(myAutoFocusCallback); //鑷姩鑱氱劍
  283. myCamera.setOneShotPreviewCallback(StandardCamera.this); //onPreviewFrame閲屼細鎺ュ彈鍒版暟鎹�?           myCamera.stopPreview(); //鍋滄棰勮
  284. flag = false;
  285. try {
  286. Thread.sleep(1000);
  287. } catch (InterruptedException e) {
  288. // TODO Auto-generated catch block
  289. e.printStackTrace();
  290. }
  291. }
  292. }
  293. }
  294. public void onPreviewFrame(byte[] data, Camera camera) {
  295. // TODO Auto-generated method stub
  296. }
  297. }

需要注意的有以下几点:

1,为了让程序适用不同的手机,onCreate函数里用如下代码初始化SurfaceView的大小,避免以前写死的方法:

public void initView(){
  mPreviewSV = (SurfaceView)findViewById(R.id.previewSV);
  WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
  Display display = wm.getDefaultDisplay();
        LayoutParams lpSV = mPreviewSV.getLayoutParams();
        lpSV.width = display.getWidth();
        lpSV.height = (int) ((float)display.getHeight()*0.75);
        mPreviewSV.setLayoutParams(lpSV);

mPhotoImgBtn = (ImageButton)findViewById(R.id.photoImgBtn);
  LayoutParams lp = mPhotoImgBtn.getLayoutParams();
  lp.width = 240;
  lp.height = 240;  
  mPhotoImgBtn.setLayoutParams(lp);    
  mPhotoImgBtn.setOnClickListener(new PhotoOnClickListener());
  mPhotoImgBtn.setOnTouchListener(new MyOnTouchListener());
 }

2,关于ZoomBar的代码片段很简短,如下:

mPhotoImgBtn = (ImageButton)findViewById(R.id.photoImgBtn);
  LayoutParams lp = mPhotoImgBtn.getLayoutParams();
  lp.width = 240;
  lp.height = 240;  
  mPhotoImgBtn.setLayoutParams(lp);    
  mPhotoImgBtn.setOnClickListener(new PhotoOnClickListener());
  mPhotoImgBtn.setOnTouchListener(new MyOnTouchListener());
 }
  //添加ZoomBar
  mZoomBar = (SeekBar)findViewById(R.id.seekbar_zoom);
  mZoomBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }
   
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }
   
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    // TODO Auto-generated method stub
    Parameters p = myCamera.getParameters();
    p.setZoom(progress);
    myCamera.setParameters(p);
   }
  });

3,在initCamera函数里,查询camera支持的聚焦模式,如果带连续视频聚焦则使用连续视频聚焦,否则使用自动聚焦:

mPhotoImgBtn = (ImageButton)findViewById(R.id.photoImgBtn);
  LayoutParams lp = mPhotoImgBtn.getLayoutParams();
  lp.width = 240;
  lp.height = 240;  
  mPhotoImgBtn.setLayoutParams(lp);    
  mPhotoImgBtn.setOnClickListener(new PhotoOnClickListener());
  mPhotoImgBtn.setOnTouchListener(new MyOnTouchListener());
 }
List<String> focuseMode = (myParam.getSupportedFocusModes());
   for(int i=0; i<focuseMode.size(); i++){
    Log.i(tag, focuseMode.get(i));
    if(focuseMode.get(i).contains("continuous")){
     myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    }
    else{
     myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    }
   }

4,同样在initCamera函数里,设置ZoomBar的最大值:
//设置mZoomBar的最大值
   mZoomBar.setMax(myParam.getMaxZoom());

后续将写专文分析Camera4.0的源码,并且模仿到自己的代码中!

最新文章

  1. iOS 开发之SVN提交问题解决
  2. 敏捷软件开发 Agile software Development(转)
  3. JavaScript DOM 编程艺术(第2版)读书笔记 (7)
  4. Java数据结构之树和二叉树(2)
  5. (转) 读取xml文件转成List&lt;T&gt;对象的两种方法
  6. 信息安全实验四:information-security
  7. VS2013编译libcurl
  8. IE6下a标签上发送ajax请求总是error
  9. perl 取类里的成员变量
  10. 查看内存和cpu
  11. 详解Java的自动装箱与拆箱(Autoboxing and unboxing)
  12. C 线性表的链式存储实现及插入、删除等操作示例
  13. SPOJ1811 LCS - Longest Common Substring(后缀自动机)
  14. 说说GIL
  15. AVL平衡二叉树实现
  16. MySQL(十二)游标和触发器
  17. php 页面间传递数据
  18. VMWARE安装centos6 http://www.centoscn.com/image-text/setup/2013/0816/1263.html
  19. c++ 创建二叉树
  20. DM368 UBL和u-boot的裁剪

热门文章

  1. HTML页面跳转的5种方式
  2. 微软BI 之SSRS 系列 - 如何实现报表标签的本地化 - 中文和英文的互换
  3. SqlServer插入1000条记录
  4. Cocos开发小游戏如何实现微信排行榜
  5. JNI 数据类型转换
  6. Webwork【05】请求跳转前 xwork.xml 的读取
  7. java 线程池线程忙碌且阻塞队列也满了时给一个拒接的详细报告
  8. 【转】UIAutomator源码分析之启动和运行
  9. Light OJ 1406 Assassin`s Creed 状态压缩DP+强连通缩点+最小路径覆盖
  10. 生命周期方法调用,以及在onStop()方法中处理草稿信息