最近项目用到自定义相机,就上网学习了一番,看看如何实现
一.布局代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 <?xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" > <View android:id= "@+id/homeCustom_cover_top_view" android:layout_width= "match_parent" android:layout_height= "0dp" android:layout_alignParentTop= "true" android:background= "@color/black" /> <View android:id= "@+id/homeCustom_cover_bottom_view" android:layout_width= "match_parent" android:layout_height= "0dp" android:background= "@color/black" /> <View android:id= "@+id/home_camera_cover_top_view" android:layout_width= "match_parent" android:layout_height= "0dp" android:layout_alignParentTop= "true" android:background= "@color/black" /> <View android:id= "@+id/home_camera_cover_bottom_view" android:layout_width= "match_parent" android:layout_height= "0dp" android:background= "@color/black" /> <FrameLayout android:layout_width= "match_parent" android:layout_height= "match_parent" > <SurfaceView android:id= "@+id/surfaceView" android:layout_width= "match_parent" android:layout_height= "match_parent" /> </FrameLayout> <TextView android:id= "@+id/camera_delay_time_text" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_above= "@+id/homecamera_bottom_relative" android:text= "" android:textColor= "@color/white" android:textSize= "14sp" android:layout_marginLeft= "20dp" /> <LinearLayout android:id= "@+id/home_custom_top_relative" android:layout_width= "match_parent" android:layout_height= "44dp" android:layout_alignParentTop= "true" android:background= "@color/black" android:gravity= "center_vertical" android:orientation= "horizontal" android:visibility= "gone" > <ImageView android:id= "@+id/camera_close" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_weight= "1" android:padding= "10dp" android:src= "@mipmap/s_icon_position_delete_colour" /> <ImageView android:id= "@+id/flash_light" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_weight= "1" android:padding= "10dp" android:src= "@mipmap/s_icon_position_delete_colour" /> <ImageView android:id= "@+id/camera_square" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_weight= "1" android:background= "#00000000" android:padding= "10dp" android:src= "@mipmap/s_icon_position_delete_colour" /> <ImageView android:id= "@+id/camera_delay_time" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_weight= "1" android:padding= "10dp" android:src= "@mipmap/s_icon_position_delete_colour" /> <ImageView android:id= "@+id/camera_frontback" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_weight= "1" android:padding= "10dp" android:src= "@mipmap/s_icon_position_delete_colour" /> </LinearLayout> <RelativeLayout android:id= "@+id/homecamera_bottom_relative" android:layout_width= "match_parent" android:layout_height= "wrap_content" android:paddingTop= "20dp" android:paddingBottom= "20dp" android:background= "@color/transparent_grey" android:layout_alignParentBottom= "true" android:layout_alignParentLeft= "true" android:layout_alignParentStart= "true" > <RelativeLayout android:layout_width= "match_parent" android:layout_height= "wrap_content" android:layout_centerInParent= "true" > <ImageView android:id= "@+id/img_camera" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_centerInParent= "true" android:src= "@mipmap/changing_photograph_selected" /> </RelativeLayout> </RelativeLayout> </RelativeLayout>代码实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 public class CameraActivity extends Activity implements SurfaceHolder.Callback, View.OnClickListener { private Camera mCamera; private SurfaceView surfaceView; private SurfaceHolder mHolder; private int mCameraId = 0 ; private Context context; //屏幕宽高 private int screenWidth; private int screenHeight; private LinearLayout home_custom_top_relative; private ImageView camera_delay_time; private View homeCustom_cover_top_view; private View homeCustom_cover_bottom_view; private View home_camera_cover_top_view; private View home_camera_cover_bottom_view; private ImageView flash_light; private TextView camera_delay_time_text; private ImageView camera_square; private int index; //底部高度 主要是计算切换正方形时的动画高度 private int menuPopviewHeight; //动画高度 private int animHeight; //闪光灯模式 0:关闭 1: 开启 2: 自动 private int light_num = 0 ; //延迟时间 private int delay_time; private int delay_time_temp; private boolean isview = false ; private boolean is_camera_delay; private ImageView camera_frontback; private ImageView camera_close; private RelativeLayout homecamera_bottom_relative; private ImageView img_camera; private int picHeight; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_camera); context = this ; initView(); camera_delay_time_text.setText(Constant.mAddress); initData(); } private void initView() { surfaceView = (SurfaceView) findViewById(R.id.surfaceView); Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.gray)); paint.setAntiAlias( true ); Canvas canvas = new Canvas(); canvas.drawPaint(paint); surfaceView.draw(canvas); mHolder = surfaceView.getHolder(); mHolder.addCallback( this ); img_camera = (ImageView) findViewById(R.id.img_camera); img_camera.setOnClickListener( this ); //关闭相机界面按钮 camera_close = (ImageView) findViewById(R.id.camera_close); camera_close.setOnClickListener( this ); //top 的view home_custom_top_relative = (LinearLayout) findViewById(R.id.home_custom_top_relative); home_custom_top_relative.setAlpha( 0 .5f); //前后摄像头切换 camera_frontback = (ImageView) findViewById(R.id.camera_frontback); camera_frontback.setOnClickListener( this ); //延迟拍照时间 camera_delay_time = (ImageView) findViewById(R.id.camera_delay_time); camera_delay_time.setOnClickListener( this ); //正方形切换 camera_square = (ImageView) findViewById(R.id.camera_square); camera_square.setOnClickListener( this ); //切换正方形时候的动画 homeCustom_cover_top_view = findViewById(R.id.homeCustom_cover_top_view); homeCustom_cover_bottom_view = findViewById(R.id.homeCustom_cover_bottom_view); homeCustom_cover_top_view.setAlpha( 0 .5f); homeCustom_cover_bottom_view.setAlpha( 0 .5f); //拍照时动画 home_camera_cover_top_view = findViewById(R.id.home_camera_cover_top_view); home_camera_cover_bottom_view = findViewById(R.id.home_camera_cover_bottom_view); home_camera_cover_top_view.setAlpha( 1 ); home_camera_cover_bottom_view.setAlpha( 1 ); //闪光灯 flash_light = (ImageView) findViewById(R.id.flash_light); flash_light.setOnClickListener( this ); camera_delay_time_text = (TextView) findViewById(R.id.camera_delay_time_text); homecamera_bottom_relative = (RelativeLayout) findViewById(R.id.homecamera_bottom_relative); } private void initData() { DisplayMetrics dm = context.getResources().getDisplayMetrics(); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; menuPopviewHeight = screenHeight - screenWidth * 4 / 3 ; animHeight = (screenHeight - screenWidth - menuPopviewHeight - SystemUtils.dp2px(context, 44 )) / 2 ; //相机取景框为宽高比3:4 限制底部控件的高度是剩余部分 RelativeLayout.LayoutParams bottomParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, menuPopviewHeight); bottomParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); // homecamera_bottom_relative.setLayoutParams(bottomParam); } private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { int what = msg.what; switch (what) { case AppConstant.WHAT.SUCCESS: if (delay_time > 0 ) { camera_delay_time_text.setText( "" + delay_time); } try { if (delay_time == 0 ) { captrue(); is_camera_delay = false ; camera_delay_time_text.setVisibility(View.VISIBLE); } } catch (Exception e) { return ; } break ; case AppConstant.WHAT.ERROR: is_camera_delay = false ; break ; } } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_camera: if (isview) { if (delay_time == 0 ) { switch (light_num) { case 0 : //关闭 CameraUtil.getInstance().turnLightOff(mCamera); break ; case 1 : CameraUtil.getInstance().turnLightOn(mCamera); break ; case 2 : //自动 CameraUtil.getInstance().turnLightAuto(mCamera); break ; } captrue(); } else { camera_delay_time_text.setVisibility(View.VISIBLE); camera_delay_time_text.setText(String.valueOf(delay_time)); is_camera_delay = true ; new Thread( new Runnable() { @Override public void run() { while (delay_time > 0 ) { //按秒数倒计时 try { Thread.sleep( 1000 ); } catch (InterruptedException e) { mHandler.sendEmptyMessage(AppConstant.WHAT.ERROR); return ; } delay_time--; mHandler.sendEmptyMessage(AppConstant.WHAT.SUCCESS); } } }).start(); } isview = false ; } break ; case R.id.camera_square: if (index == 0 ) { camera_square_0(); } else if (index == 1 ) { camera_square_1(); } break ; //前后置摄像头拍照 case R.id.camera_frontback: switchCamera(); break ; //退出相机界面 释放资源 case R.id.camera_close: if (is_camera_delay) { Toast.makeText(CameraActivity. this , "正在拍照请稍后..." , Toast.LENGTH_SHORT).show(); return ; } finish(); break ; //闪光灯 case R.id.flash_light: if (mCameraId == 1 ) { //前置 // ToastFactory.showLongToast(context, "请切换为后置摄像头开启闪光灯"); return ; } Camera.Parameters parameters = mCamera.getParameters(); switch (light_num) { case 0 : //打开 light_num = 1 ; flash_light.setImageResource(R.mipmap.s_icon_position_delete_nor); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); //开启 mCamera.setParameters(parameters); break ; case 1 : //自动 light_num = 2 ; parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); mCamera.setParameters(parameters); flash_light.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; case 2 : //关闭 light_num = 0 ; //关闭 parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(parameters); flash_light.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; } break ; //延迟拍照时间 case R.id.camera_delay_time: switch (delay_time) { case 0 : delay_time = 3 ; delay_time_temp = delay_time; camera_delay_time.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; case 3 : delay_time = 5 ; delay_time_temp = delay_time; camera_delay_time.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; case 5 : delay_time = 10 ; delay_time_temp = delay_time; camera_delay_time.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; case 10 : delay_time = 0 ; delay_time_temp = delay_time; camera_delay_time.setImageResource(R.mipmap.s_icon_position_delete_nor); break ; } } } public void switchCamera() { releaseCamera(); mCameraId = (mCameraId + 1 ) % mCamera.getNumberOfCameras(); mCamera = getCamera(mCameraId); if (mHolder != null ) { startPreview(mCamera, mHolder); } } /** * 正方形拍摄 */ public void camera_square_0() { camera_square.setImageResource(R.mipmap.s_icon_position_delete_nor); //属性动画 ValueAnimator anim = ValueAnimator.ofInt( 0 , animHeight); anim.setDuration( 300 ); anim.addUpdateListener( new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int currentValue = Integer.parseInt(animation.getAnimatedValue().toString()); RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(screenWidth, currentValue); Params.setMargins( 0 , SystemUtils.dp2px(context, 44 ), 0 , 0 ); homeCustom_cover_top_view.setLayoutParams(Params); RelativeLayout.LayoutParams bottomParams = new RelativeLayout.LayoutParams(screenWidth, currentValue); bottomParams.setMargins( 0 , screenHeight - menuPopviewHeight - currentValue, 0 , 0 ); homeCustom_cover_bottom_view.setLayoutParams(bottomParams); } }); anim.start(); homeCustom_cover_top_view.bringToFront(); home_custom_top_relative.bringToFront(); homeCustom_cover_bottom_view.bringToFront(); index++; } /** * 长方形方形拍摄 */ public void camera_square_1() { camera_square.setImageResource(R.mipmap.s_icon_position_delete_nor); ValueAnimator anim = ValueAnimator.ofInt(animHeight, 0 ); anim.setDuration( 300 ); anim.addUpdateListener( new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int currentValue = Integer.parseInt(animation.getAnimatedValue().toString()); RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(screenWidth, currentValue); Params.setMargins( 0 , SystemUtils.dp2px(context, 44 ), 0 , 0 ); homeCustom_cover_top_view.setLayoutParams(Params); RelativeLayout.LayoutParams bottomParams = new RelativeLayout.LayoutParams(screenWidth, currentValue); bottomParams.setMargins( 0 , screenHeight - menuPopviewHeight - currentValue, 0 , 0 ); homeCustom_cover_bottom_view.setLayoutParams(bottomParams); } }); anim.start(); index = 0 ; } @Override protected void onResume() { super .onResume(); if (mCamera == null ) { mCamera = getCamera(mCameraId); if (mHolder != null ) { startPreview(mCamera, mHolder); } } } @Override protected void onPause() { super .onPause(); releaseCamera(); } /** * 获取Camera实例 * * @return */ private Camera getCamera( int id) { Camera camera = null ; try { camera = Camera.open(id); } catch (Exception e) { } return camera; } /** * 预览相机 */ private void startPreview(Camera camera, SurfaceHolder holder) { try { setupCamera(camera); camera.setPreviewDisplay(holder); //亲测的一个方法 基本覆盖所有手机 将预览矫正 CameraUtil.getInstance().setCameraDisplayOrientation( this , mCameraId, camera); // camera.setDisplayOrientation(90); camera.startPreview(); isview = true ; } catch (IOException e) { e.printStackTrace(); } } private void captrue() { mCamera.takePicture( null , null , new Camera.PictureCallback() { @Override public void onPictureTaken( byte [] data, Camera camera) { isview = false ; //将data 转换为位图 或者你也可以直接保存为文件使用 FileOutputStream //这里我相信大部分都有其他用处把 比如加个水印 后续再讲解 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0 , data.length); Bitmap saveBitmap = CameraUtil.getInstance().setTakePicktrueOrientation(mCameraId, bitmap); saveBitmap = Bitmap.createScaledBitmap(saveBitmap, screenWidth, picHeight, true ); if (index == 1 ) { //正方形 animHeight(动画高度) saveBitmap = Bitmap.createBitmap(saveBitmap, 0 , animHeight + SystemUtils.dp2px(context, 44 ), screenWidth, screenWidth); } else { //正方形 animHeight(动画高度) saveBitmap = Bitmap.createBitmap(saveBitmap, 0 , 0 , screenWidth, screenWidth * 4 / 3 ); } String img_path = getExternalFilesDir(Environment.DIRECTORY_DCIM).getPath() + File.separator + System.currentTimeMillis() + ".jpg" ; CameraBitmapUtils.saveJPGE_After(context, watermarkBitmap(saveBitmap, null , Constant.mAddress), img_path, 100 ); if (!bitmap.isRecycled()) { bitmap.recycle(); } if (!saveBitmap.isRecycled()) { saveBitmap.recycle(); } AppConstant.IMG_PATH = img_path; Intent intent = new Intent(CameraActivity. this , FieldSignActivity. class ); // intent.putExtra("data", saveBitmap); intent.putExtra(AppConstant.KEY.IMG_PATH, img_path); intent.putExtra(AppConstant.KEY.PIC_WIDTH, "1" ); intent.putExtra(AppConstant.KEY.PIC_HEIGHT, picHeight); setResult(AppConstant.RESULT_CODE.RESULT_OK, intent); finish(); //这里打印宽高 就能看到 CameraUtil.getInstance().getPropPictureSize(parameters.getSupportedPictureSizes(), 200); // 这设置的最小宽度影响返回图片的大小 所以这里一般这是1000左右把我觉得 // Log.d("bitmapWidth==", bitmap.getWidth() + ""); // Log.d("bitmapHeight==", bitmap.getHeight() + ""); } }); } public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark, String title) { if (src == null ) { return null ; } int w = src.getWidth(); int h = src.getHeight(); //需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了 Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); // 创建一个新的和SRC长度宽度一样的位图 Canvas cv = new Canvas(newb); cv.drawBitmap(src, 0 , 0 , null ); // 在 0,0坐标开始画入src Paint paint = new Paint(); //加入图片 if (watermark != null ) { int ww = watermark.getWidth(); int wh = watermark.getHeight(); paint.setAlpha( 50 ); cv.drawBitmap(watermark, w - ww + 5 , h - wh + 5 , paint); // 在src的右下角画入水印 } //加入文字 if (title != null ) { String familyName = "黑体" ; // Typeface font = Typeface.create(familyName,Typeface.NORMAL); TextPaint textPaint = new TextPaint(); textPaint.setColor(Color.WHITE); // textPaint.setTypeface(font); textPaint.setTextSize( 30 ); //这里是自动换行的 StaticLayout layout = new StaticLayout(title, textPaint, w, Layout.Alignment.ALIGN_NORMAL, 1 .0F, 0 .0F, true ); cv.translate( 0 , h / 2 + 50 ); layout.draw(cv); } cv.save(Canvas.ALL_SAVE_FLAG); // 保存 cv.restore(); // 存储 return newb; } /** * 设置 */ private void setupCamera(Camera camera) { Camera.Parameters parameters = camera.getParameters(); if (parameters.getSupportedFocusModes().contains( Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸 Camera.Size previewSize = CameraUtil.getInstance().getPropSizeForHeight(parameters.getSupportedPreviewSizes(), 800 ); parameters.setPreviewSize(previewSize.width, previewSize.height); Camera.Size pictrueSize = CameraUtil.getInstance().getPropSizeForHeight(parameters.getSupportedPictureSizes(), 800 ); parameters.setPictureSize(pictrueSize.width, pictrueSize.height); camera.setParameters(parameters); /** * 设置surfaceView的尺寸 因为camera默认是横屏,所以取得支持尺寸也都是横屏的尺寸 * 我们在startPreview方法里面把它矫正了过来,但是这里我们设置设置surfaceView的尺寸的时候要注意 previewSize.height<previewSize.width * previewSize.width才是surfaceView的高度 * 一般相机都是屏幕的宽度 这里设置为屏幕宽度 高度自适应 你也可以设置自己想要的大小 * */ picHeight = (screenWidth * pictrueSize.width) / pictrueSize.height; FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(screenWidth, (screenWidth * pictrueSize.width) / pictrueSize.height); //这里当然可以设置拍照位置 比如居中 我这里就置顶了 //params.gravity = Gravity.CENTER; // surfaceView.setLayoutParams(params); } /** * 释放相机相应资源 */ private void releaseCamera() { if (mCamera != null ) { mCamera.setPreviewCallback( null ); mCamera.stopPreview(); mCamera.release(); mCamera = null ; } } @Override public void surfaceCreated(SurfaceHolder holder) { startPreview(mCamera, holder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { mCamera.stopPreview(); startPreview(mCamera, holder); } @Override public void surfaceDestroyed(SurfaceHolder holder) { releaseCamera(); } }