Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 View 實戰:仿去哪兒網按壓顯示指紋並縮放的效果

編輯:關於 Android 程式設計

仔細看去哪兒網 App 的首頁,那些 Win8 風格的方塊在按下時有兩個細節很打眼:圖片會微微縮放,同時浮現一層指紋圖案,真的像手指按在玻璃上一樣,質感立刻拉滿。今天我們就來拆解這個效果該怎麼做。

1. 先看效果

2. 準備一張指紋素材

關鍵素材是指紋圖,必須是 PNG 透明背景。因為透明區域在這裡看不出效果,所以連背景一起展示如下:

3. 自定義 TouchFingerImageView

整體思路很直白:繼承 ImageView,在 onDraw 中先畫原圖,若處於按下狀態則在中間疊畫指紋;再在 onTouchEvent 中透過 ScaleAnimation 做縮放回饋。程式碼如下,註解寫得比較細:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

/**
 * 自定義仿去哪兒手指按下圖片縮放並顯示指紋的效果
 */
public class TouchFingerImageView extends ImageView {

    /** 指紋圖片 */
    private Bitmap fingerBitmap;

    /** 圖片是否處於按下狀態 */
    private boolean state = false;

    /** 點擊事件 */
    private OnClickListener onClickListener;

    public TouchFingerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 取得並縮放指紋圖
        fingerBitmap = zoom(
                BitmapFactory.decodeResource(getResources(), R.mipmap.finger),
                300, 300);
    }

    /**
     * 圖片縮放
     *
     * @param bitmap    原始圖片
     * @param newWidth  縮放後寬度
     * @param newHeight 縮放後高度
     * @return 縮放後的 Bitmap
     */
    public Bitmap zoom(Bitmap bitmap, int newWidth, int newHeight) {
        float width = bitmap.getWidth();
        float height = bitmap.getHeight();

        // 計算寬高縮放比例
        float rateWidth = ((float) newWidth) / width;
        float rateHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(rateWidth, rateHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, (int) width, (int) height,
                matrix, true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 取出原始資源圖片
        Bitmap bitmap = ((BitmapDrawable) this.getDrawable()).getBitmap();

        // 先畫底圖(縮放至控制項尺寸)
        canvas.drawBitmap(zoom(bitmap, getWidth(), getHeight()), 0, 0, null);

        if (state) {
            Matrix matrix = new Matrix();
            // 平移讓指紋居中顯示
            matrix.postTranslate(
                    this.getWidth() / 2 - fingerBitmap.getWidth() / 2,
                    this.getHeight() / 2 - fingerBitmap.getHeight() / 2);
            canvas.drawBitmap(fingerBitmap, matrix, null);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float begin = 1.0f;
        float end = 0.95f;

        // 按下時的收縮動畫
        Animation beginAnimation = new ScaleAnimation(begin, end, begin, end,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        // 抬起時的還原動畫
        Animation finishAnimation = new ScaleAnimation(end, begin, end, begin,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

        beginAnimation.setDuration(200);
        beginAnimation.setFillAfter(true); // 停留在最後一幀
        finishAnimation.setDuration(200);
        finishAnimation.setFillAfter(true);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startAnimation(beginAnimation);
                state = true;
                invalidate();
                if (onClickListener != null) {
                    onClickListener.onClick(this);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                startAnimation(finishAnimation);
                state = false;
                invalidate();
                break;
        }
        return true;
    }

    @Override
    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }
}

有兩個細節值得留意:一是 onTouchEvent 回傳 true,把事件消費掉,避免父容器攔截;二是 ACTION_CANCEL 也要處理,否則使用者手指滑出畫面後狀態會卡在按下。

4. 使用方式

佈局檔中直接當作普通 ImageView 使用,透過 layout_weight 做等分排列:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#393939"
    android:orientation="vertical"
    tools:context="cn.bluemobi.dylan.touchfingerimageview.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <cn.bluemobi.dylan.touchfingerimageview.TouchFingerImageView
            android:id="@+id/tfiv1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:scaleType="centerCrop"
            android:src="@mipmap/iv1" />

        <cn.bluemobi.dylan.touchfingerimageview.TouchFingerImageView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_weight="2"
            android:scaleType="centerCrop"
            android:src="@mipmap/iv2" />
    </LinearLayout>

    <!-- 其餘列結構相同,重複即可 -->
</LinearLayout>

Activity 中的用法與一般控制項完全一致:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.tfiv1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "點擊了第一個",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

5. 源碼

GitHub 源碼:https://github.com/linglongxin24/TouchFingerImageView

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved