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

Android 開發實戰:模擬 3D Touch 彈出效果完整教程

編輯:關於 Android 開發

Android 開發實戰:模擬 3D Touch 彈出效果

3D Touch 是什麼效果,用過 iPhone 6s 的朋友應該都心中有數。本篇就來一步步復刻這個效果。

先看一下最終實現的效果圖:

再來一張(質量不太高的)動圖:

這張 GIF 效果一般,實際運行其實非常順滑,而且模糊效果應該像第一張圖那樣。後文會放出完整代碼,感興趣的可以跑起來親眼看看。

先說思路,要實現這個效果,只需掌握幾個關鍵點:

  • 屏幕截圖
  • 高斯模糊
  • 動態添加視圖
  • 彈出動畫
  • 處理長按事件

整體流程是:當用戶長按某個 Item 時,先截取當前屏幕的圖片,對其進行高斯模糊後覆蓋到整個布局之上(連 Toolbar 也一并覆蓋),界面模糊效果便出現了;接著動態向界面添加一個 CardView 來呈現對應 Item 的布局,讓它浮現在被點擊的 Item 上方;最後再補上一個 3D Touch 風格的彈出動畫即可。

下面一步步完成整個流程。

① 屏幕截圖

這部分相對簡單,獲取當前屏幕內容的 Bitmap 有現成方法:

private Bitmap getScreenImage() {
    // 截取一張屏幕圖片
    View view = root;
    view.setBackgroundColor(Color.WHITE);
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0,
            view.getWidth(), view.getHeight());
    view.destroyDrawingCache();
    return bitmap;
}

先看布局文件:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.fndroid.threedtouchdemo.MainActivity">

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:title="@string/app_name"
            app:titleTextColor="#fff"/>

        <ListView
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/item"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/cover"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:translationZ="5dp"
        app:cardCornerRadius="10dp"/>
</FrameLayout>

最外層使用 FrameLayout,是因為需要往整個布局上覆蓋一張高斯模糊後的截圖。最下方的 ImageView 就是用來做模糊效果的,初始時將它的 alpha 設為 0 讓其透明即可;而 CardView 則是稍後要彈出的控件。截圖的 root 取的是 FrameLayout 下的 LinearLayout,這樣才能讓 Toolbar 也一并模糊化。

② 高斯模糊

這個在上一篇《動態高斯模糊怎麼做》中已講過,這裡給出對應代碼:

private Bitmap blur(Bitmap bitmap, float radius) {
    Bitmap output = Bitmap.createBitmap(bitmap); // 創建輸出圖片
    RenderScript rs = RenderScript.create(this); // 構建 RenderScript 對象
    ScriptIntrinsicBlur gaussianBlue = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // 創建高斯模糊腳本
    Allocation allIn = Allocation.createFromBitmap(rs, bitmap); // 開辟輸入內存
    Allocation allOut = Allocation.createFromBitmap(rs, output); // 開辟輸出內存
    gaussianBlue.setRadius(radius); // 設置模糊半徑,范圍 0f < radius <= 25f
    gaussianBlue.setInput(allIn); // 設置輸入內存
    gaussianBlue.forEach(allOut); // 執行模糊並填入輸出內存
    allOut.copyTo(output); // 將輸出內存編碼為 Bitmap
    rs.destroy(); // 關閉 RenderScript 對象,API>=23 則使用 rs.releaseAllContexts()
    return output;
}

配置對應 Module 的 build.gradle:

defaultConfig {
    ...
    renderscriptTargetApi 18
    renderscriptSupportModeEnabled true
}

③ 彈出視圖

這個視圖需要把 Item 的 View 添加到 CardView 中,並讓 CardView 定位在對應 Item 的位置之上:

// 顯示對應的卡片
private void showView(int position, View view) {
    newView = LayoutInflater.from(this).inflate(R.layout.item, null); // 加載 Item 布局
    TextView tv = (TextView) newView.findViewById(R.id.item_tv); // 獲取對應控件
    tv.setText(data.get(position).get("name")); // 回填數據
    newView.setBackgroundColor(Color.WHITE); // 設置卡片樣式
    // 位置通過 marginTop 計算
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(view.getWidth() - 30, view.getHeight());
    params.topMargin = (int) (view.getY() + mToolbar.getHeight()); // marginTop 為 item 的 Y 加上 toolbar 高度
    params.leftMargin = 15;
    params.rightMargin = 15;
    mCardView.setVisibility(View.VISIBLE);
    mCardView.setLayoutParams(params);
    mCardView.addView(newView, view.getLayoutParams()); // 加載 View 並設置樣式
    startAnimate(mCardView); // 播放動畫
}

這裡不能直接把 item 的 view 加載進 CardView,因為 item 的 View 已有父布局,直接添加會拋異常。解法是重新 inflate 一個對應布局並填充數據,接著設置卡片的位置與大小,讓它顯示在對應 Item 上方。

④ 彈出動畫

這部分比較簡單,直接用 PropertyValuesHolder 做一個彈出與收縮的動畫。因為需要同時縮放 X 和 Y:

private void startAnimate(CardView cardView) {
    PropertyValuesHolder pyhScaleX = PropertyValuesHolder.ofFloat("scaleX", 0.1f, 1.05f);
    PropertyValuesHolder pyhScaleY = PropertyValuesHolder.ofFloat("scaleY", 0.1f, 1.05f);
    ObjectAnimator animator_out = ObjectAnimator.ofPropertyValuesHolder(mCardView, pyhScaleX, pyhScaleY);
    animator_out.setInterpolator(new AccelerateDecelerateInterpolator());
    animator_out.setDuration(350);
    PropertyValuesHolder pyhScaleX2 = PropertyValuesHolder.ofFloat("scaleX", 1.05f, 1f);
    PropertyValuesHolder pyhScaleY2 = PropertyValuesHolder.ofFloat("scaleY", 1.05f, 1f);
    ObjectAnimator animator_in = ObjectAnimator.ofPropertyValuesHolder(mCardView, pyhScaleX2, pyhScaleY2);
    animator_in.setInterpolator(new AccelerateDecelerateInterpolator());
    animator_in.setDuration(100);
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playSequentially(animator_out, animator_in); // 按順序執行兩個動畫
    animatorSet.start();
}

⑤ 監聽長按事件

這裡用 ListView 簡化,直接借助已有的監聽器即可:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    mCover.setImageBitmap(blur(blur(getScreenImage(), 25f), 25f)); // 對截圖做兩次高斯模糊
    mCover.setVisibility(View.VISIBLE);
    mCover.setImageAlpha(0);
    new Thread(new Runnable() {
        int progress = 50;
        @Override
        public void run() {
            while (progress < 255) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = new Message();
                msg.obj = progress++;
                mHandler.sendMessage(msg);
            }
        }
    }).start();
    showView(position, view);
    return true;
}

第 3 行調用了兩次 blur 方法對圖片做高斯模糊。由於每次高斯模糊的最大半徑是 25,若要做到接近 iOS 那樣的模糊效果,25 是不夠的,所以可以對模糊後的圖片再模糊一次。對比圖如下(左為兩次模糊,右為一次):

源碼地址:Github

感謝支持。

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