---
title: "【2013.07.17】自定义相机对焦框等"
author: "crazysumer"
date: "2013-07-17T22:58:02Z"
tags: []
categories: ["移动开发"]
slug: "2013-07-17"
draft: false
lastmod: "2013-07-17T23:00:16Z"
id: 1908939
url: "https://crazysumer.iteye.com/blog/1908939"
---

1\.

好开心，自定义相机的对焦框出来了，虽然感觉有点蛋筒。之前也想用画图画的 ，可是因为蛋筒的数据传递问题抛弃了自定义SurfaceView，在Acivity中不能override onDraw方法，暂时不知道可行性。

 

所以采取的方式是，在相机预览的界面的点击位置显示一个对焦框的图片。这个图片位置的设定，没有直接的通过中心点坐标设置的方法，只能绕道，获得触摸点坐标后，设置图片的Margin。

 

# ViewGroup.MarginLayoutParams 中有[setMargins](http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html#setMargins%28int,%20int,%20int,%20int%29)(int left, int top, int right, int bottom)方法

 

可以设置控件在界面上的上下左右margin。

 

我要动态显示的ImageView在一个LinearLayout中的FrameLayout中，所以给ImageView设置Parameters的时候用到

# FrameLayout.LayoutParams

 

关键的代码

```
	/**
	 * @描述 自动对焦
	 * */
	AutoFocusCallback autoFocus = new AutoFocusCallback() {
		

		@Override
		public void onAutoFocus(boolean success, Camera camera) {

			if (success) {
				ViewGroup.MarginLayoutParams margin = new ViewGroup.MarginLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				margin.setMargins((int)(x-46.5), (int)(y-46.5), 0, 0);
				FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
						margin);
				focus.setLayoutParams(params);
				System.out.println(focus.getLayoutParams().getClass());
				focus.setVisibility(ImageView.VISIBLE);
				/*
				 * 2秒后，自动对焦框消失
				 * */ 
				Handler timeHandler = new Handler();
				timeHandler.post(new Runnable() {

					@Override
					public void run() {
						try {
							Thread.sleep(2000);
							if (0 == focus.getVisibility()) {
								focus.setVisibility(ImageView.GONE);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}
				});
			}
		}

	};
```

 

 

2\. 拍完照后，在当前界面有一个ScrollView对已经拍摄的照片的缩略图的展示，怎样让那个ScrollView每次滚动到当前拍摄的界面呢。当然用到ScrollView的[smoothScrollTo](http://developer.android.com/reference/android/widget/ScrollView.html#smoothScrollTo%28int,%20int%29)(int x, int y)方法，把它放到一个Runnable中去执行。

每个ImageView都有自己的高度，记录ImageView的个数，x=0,y=ImageView的高度×ImageView的个数。

感谢eoe某用户 ![吻](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-kiss.gif "吻")

 

关键代码

```
	Handler smoothHandler = new Handler();
				smoothHandler.post(new Runnable() {

					@Override
					public void run() {
						int offset = iv.getMeasuredHeight()
								* photoPromts.length;
						if (offset < 0) {
							offset = 0;
						}
						scrollView.smoothScrollTo(0, offset);
					}
				});
```

 

 

3.在ScrollView中有一个LinearLayout,在这个LinearLayout中才是多个ImageView，怎样给这些ImageView设置监听，能够在点击他们时可以预览大图呢。直接给它setOnclickListener就可以了，只不过我这里的ImageView是final类型，会报

The final local variable iv cannot be assigned, since it is defined in an enclosing type 编译错。

就再定义一个ImageView去代表它