Suck the cat with code! This paper is participating in[Cat Essay Campaign]

Train of thought

After seeing the activity, I searched the cat tickling app on the Internet and found the introduction of snapCat app. Based on the idea of the app, I used a GIF to attract the cat’s attention and secretly took a picture when the cat’s paw was on the picture. See if I can get some good pictures of Gege.

Step1: secretly take pictures

Use Android.hardware.Camera with SurfaceView.

  1. Add a preview screen to the layout file (startpreview, although cats don’t need to see previews)

Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture.

<SurfaceView
    android:id="@+id/sf"
    android:layout_width="1dp"
    android:layout_height="1dp" />
Copy the code
  1. Example Initialize the front camera
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
    Camera.getCameraInfo(camIdx, cameraInfo);
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        try {
            myCamera = Camera.open(camIdx);
        } catch(RuntimeException e) { e.printStackTrace(); }}}try {
    myCamera.setPreviewDisplay(surfaceView.getHolder());
} catch (IOException e) {
    e.printStackTrace();
    myCamera.stopPreview();
    myCamera.release();
    myCamera = null;
}

myCamera.startPreview();
Copy the code
  1. Take photos and save them to an album
private void takePhoto(a) {
    myCamera.autoFocus(myAutoFocus);
    myCamera.takePicture(null.null, myPicCallback);
}
Copy the code
private Camera.AutoFocusCallback myAutoFocus = new Camera.AutoFocusCallback() {
    @Override
    public void onAutoFocus(boolean success, Camera camera) {}};Copy the code
private Camera.PictureCallback myPicCallback = new Camera.PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        // Rotate the resulting photo 270° to make it vertical
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        Matrix matrix = new Matrix();
        matrix.preRotate(270);
        bitmap = Bitmap.createBitmap(bitmap, 0.0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        saveImage(timeStamp+".jpg", bitmap); }};Copy the code
@RequiresApi(api = Build.VERSION_CODES.Q)
private void saveImage(String fileName, Bitmap bitmap) {
    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/cat/");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
        Uri uri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        if(uri ! =null) {
            OutputStream outputStream = mContext.getContentResolver().openOutputStream(uri);
            if(outputStream ! =null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream); outputStream.flush(); outputStream.close(); }}}catch(Exception e) { e.printStackTrace(); }}Copy the code

Turn off the camera

myCamera.stopPreview();
myCamera.release();
myCamera = null;
Copy the code

Step2. Attract attention

  1. Add a GIF image to the layout file
<ImageView
    android:id="@+id/image"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_centerInParent="true" />
Copy the code
Glide.with(this).asGif().load(R.mipmap.bird).into(image);
Copy the code
  1. Go to Picture – Random Move – Take a picture
image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        x = (float) (Math.random() * width);
        y = (float) (Math.random() * height);
        Path path = new Path();
        path.moveTo(x,y);
        ObjectAnimator animator = ObjectAnimator.ofFloat(v, View.X, View.Y, path);
        animator.setDuration(2000); animator.start(); takePhoto(); }});Copy the code

Width and height limit the range of random movement

int defaultMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,150,getResources().getDisplayMetrics());

width = getWindowManager().getDefaultDisplay().getWidth()-defaultMargin;
height = getWindowManager().getDefaultDisplay().getHeight()-defaultMargin;
Copy the code

The effect

Big failure… It can’t attract the attention of gege completely, there is no mobile phone in the eye, the effect of using the small picture to move is not good, then try to do the animation of the large picture, and the cat claw is not easy to trigger the click event… Put in a rough sketch…