如何在相机预览中添加矩形叠加层(应该更像矩形框)?我的应用程序包含一个按钮,单击即可打开相机。
我需要该相机预览中的叠加层。
java文件的代码是:
public class MainActivity extends Activity {
Button b;
Intent i;
Bitmap bmp;
final static int cameraData = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button);
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
}
});
}
}
布局文件如下:
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:text="click to take photo" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:layout_gravity="center" />
</LinearLayout>
首先,创建一个扩展 View 的公共类。其内部onDraw()
方法,画出你的矩形。例如:
public class Box extends View {
private Paint paint = new Paint();
Box(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) { // Override the onDraw() Method
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(10);
//center
int x0 = canvas.getWidth()/2;
int y0 = canvas.getHeight()/2;
int dx = canvas.getHeight()/3;
int dy = canvas.getHeight()/3;
//draw guide box
canvas.drawRect(x0-dx, y0-dy, x0+dx, y0+dy, paint);
}
}
然后,在相机预览 Activity 中,有一个 Box 类的实例:
Box box = new Box(this);
Finally:
addContentView(box, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
一个绿色矩形将绘制在您的相机预览上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)