android - 如何在相机应用程序中添加矩形叠加层?

标签 android overlay android-camera

如何在相机预览中添加矩形叠加层(应该更像是矩形框)?我的应用程序包含一个按钮,单击该按钮可打开相机。 我需要该相机预览中的叠加层。

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 的公共(public)类。在其 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);

最后:

addContentView(box, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

将在您的相机预览中绘制一个绿色矩形。

关于android - 如何在相机应用程序中添加矩形叠加层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14894035/

相关文章:

css - 将图像垂直/水平居中放置在另一个没有尺寸的图像上

java - android - 如何使用相机从 sd 卡获取图像

android - 使用 RoboSpice 并行执行

android - GCM 消息传递确认

google-chrome-extension - 浏览器插件/扩展/插件一次查看所有元素的 id

javascript - 覆盖 div 上的 <a href> 标记没有响应

android - 如何使用Android MediaCodec编码Camera数据(YUV420sp)

android - 使用 NDK 在 Android 中进行实时图像处理

java - Instagram 之类的 登录 Android Studio

android - Android 的 iPhone 部分索引?