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

動手寫一個自定義相機界面:圓形快門、預覽與九宮格構圖線

編輯:關於 Android 程式設計

做自定義相機時,第一個會卡住的地方往往不是預覽,而是那個圓形快門按鈕。其實不必等設計師出圖,用 layer-list 疊幾層就能做出來。

一、圓形快門背景

新建 btn_take_photo.xml,放在 res/drawable 目錄下。這個目錄專門存放自定義的 drawable 資源,可以理解為自己手寫的「背景樣式集合」。

android:shape 可取四個值:rectangle(矩形,默認)、oval(橢圓)、line(線)、ring(環)。我們要的是 oval。

思路是層層疊加:最底層一個白色橢圓撐出外圈,中間一層四周各內縮 6dp 的藍色橢圓形成內芯,最上面再壓一層直徑 1dp 的藍色描邊勾勒邊界。

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">

    <!-- 外圈:白色橢圓 -->
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/white" />
        </shape>
    </item>

    <!-- 內芯:四周內縮 6dp 的藍色橢圓 -->
    <item
        android:bottom="6dp"
        android:left="6dp"
        android:right="6dp"
        android:top="6dp">
        <shape android:shape="oval">
            <solid android:color="@color/blue" />
        </shape>
    </item>

    <!-- 邊界:藍色描邊 -->
    <item>
        <shape android:shape="oval">
            <stroke
                android:width="1dp"
                android:color="@color/blue"
                android:dashWidth="0dp" />
        </shape>
    </item>
</layer-list>

效果示意:

二、相機界面佈局

activity_take_photo.xml。要點是:SurfaceView 鋪滿全屏作為預覽底層,標題欄、底部操作欄、九宮格構圖線依次疊在上面。凡涉及相機預覽或視頻播放的場景,基本都繞不開 SurfaceView——它能在獨立線程繪製,不阻塞主線程,這對實時性要求高的相機畫面至關重要。

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

    <!-- 預覽底層 -->
    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/pic">

        <!-- 自定義標題欄 -->
        <RelativeLayout
            android:id="@+id/camera_top"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:layout_alignParentTop="true"
            android:background="@color/black">

            <ImageView
                android:id="@+id/btn_black"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_alignParentLeft="true"
                android:padding="10dp"
                android:src="@drawable/back" />

            <ImageView
                android:id="@+id/btn_change"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:padding="10dp"
                android:src="@drawable/camera_flip" />
        </RelativeLayout>

        <!-- 構圖線層 -->
        <org.personality.camera.ui.view.CameraGrid
            android:id="@+id/masking"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_above="@+id/photo_area" />

        <!-- 已拍照片縮略圖區域 -->
        <LinearLayout
            android:id="@+id/photo_area"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/panel_take_photo"
            android:orientation="horizontal" />

        <!-- 底部操作欄 -->
        <RelativeLayout
            android:id="@+id/panel_take_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@color/white"
            android:gravity="center_vertical"
            android:padding="2dp">

            <ImageView
                android:id="@+id/iv_album"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:padding="5dp"
                android:src="@drawable/camera_library" />

            <ImageView
                android:id="@+id/btn_take_photo"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerHorizontal="true"
                android:background="@drawable/btn_take_photo" />

            <ImageView
                android:id="@+id/title_btn_black"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="20dp"
                android:padding="5dp"
                android:src="@drawable/camera_back" />
        </RelativeLayout>
    </RelativeLayout>
</FrameLayout>

三、自定義構圖線 CameraGrid

專業相機界面通常會疊一層九宮格輔助線,幫助用戶對齊水平與垂直。這裡繼承 View 自己畫,好處是完全可控、開銷極小。

/**
 * 自定義 View:相機九宮格構圖線
 */
public class CameraGrid extends View {

    private int topBannerWidth = 0;
    private final Paint mPaint;
    private boolean showGrid = true;

    public CameraGrid(Context context) {
        this(context, null);
    }

    public CameraGrid(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        mPaint.setAlpha(120);      // 半透明白,避免遮擋主體
        mPaint.setStrokeWidth(1f);
        mPaint.setAntiAlias(true);
    }

    public boolean isShowGrid() {
        return showGrid;
    }

    public void setShowGrid(boolean showGrid) {
        this.showGrid = showGrid;
        invalidate();
    }

    public int getTopWidth() {
        return topBannerWidth;
    }

    public void setTopBannerWidth(int topBannerWidth) {
        this.topBannerWidth = topBannerWidth;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!showGrid) return;

        int w = getWidth();
        int h = getHeight();
        // 扣除頂部標題欄高度,讓格線落在真正的預覽區域內
        int usable = h - topBannerWidth;

        for (int i = 1; i <= 2; i++) {
            float x = w / 3f * i;
            float y = topBannerWidth + usable / 3f * i;
            canvas.drawLine(x, topBannerWidth, x, h, mPaint);          // 縱線
            canvas.drawLine(0, y, w, y, mPaint);                       // 橫線
        }
    }
}

原文的 onDraw() 是空的,只能顯示佈局佔位;上面補上了實際的畫線邏輯,並加了一個 setShowGrid() 開關,方便用戶在設置裡自行關閉構圖線。

四、接下來要做的事

界面部分到此為止,真正讓相機「活」起來還需要幾步,這裡列個清單便於自查:

1. 生命周期與 Camera 的釋放。務必在 SurfaceHolder.Callback 的 surfaceDestroyed() 中調用 camera.stopPreview() 與 camera.release(),在 onPause() 中也要兜底釋放,否則再次進入頁面會報「Camera is already in use」。

2. 前後攝像頭切換。用 Camera.getNumberOfCameras() 枚舉,再通過 CameraInfo 打開指定鏡頭,切換時需重新綁定 SurfaceHolder。

3. 對焦。給預覽區域加 setOnTouchListener,把觸摸點換算成 Rect 後調用 camera.autoFocus() 並顯示對焦框動畫。

4. 拍照與數據回傳。takePicture() 的 PictureCallback 拿到原始 JPEG 字節後,按需做方向校正(ExifInterface 讀取 Orientation)、壓縮與裁剪,再存儲或回傳。

5. 新版本 API。項目若 minSdk 允許,建議直接用 Camera2 加 TextureView 的組合。Camera1 已在 API 25 後標記為 deprecated,Camera2 對手動曝光、對焦、高速連拍的支持都更完整。

這些代碼僅供互相參考,功能仍在完善中。寫博客既是記錄自己的學習軌跡,也是把踩過的坑留給後來者少走彎路。

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