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

自定義 ImageView 實現圖片上傳進度遮罩(仿手機 QQ 效果)

編輯:關於 Android 程式設計

在聊天類應用中,圖片從選好到真正發送出去往往需要一段時間。如果能在縮略圖上蓋一層半透明遮罩、再把百分比標在中間,用戶就能一眼看出還要等多久——這正是手機 QQ 的做法。本文就來從零實現一個這樣的控件。

先看參考效果(QQ 聊天中發送圖片時的樣子):

再看本文的最終成果:

一、實現思路

原理並不複雜:繼承 ImageView,在 onDraw 中先讓系統把原圖畫好,然後用畫筆覆蓋兩個矩形——「已完成」的區域用全透明色畫一筆,相當於什麼都不畫;「未完成」的區域用半透明黑色蓋住;最後在正中央補上百分比文字。進度每次變化時調用 postInvalidate() 觸發重繪即可。

二、編寫 ProcessImageView

新建 Android 工程 ProgressImageView,然後寫出自定義控件:

package com.example.processimageview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ProcessImageView extends ImageView {

    private Paint mPaint;      // 畫筆
    private int progress = 0;  // 當前進度 0~100
    private Context context;

    public ProcessImageView(Context context) {
        super(context);
    }

    public ProcessImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProcessImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        mPaint = new Paint();
    }

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

        mPaint.setAntiAlias(true);                       // 消除鋸齒
        mPaint.setStyle(Paint.Style.FILL);

        // 未完成區域:半透明遮罩
        mPaint.setColor(Color.parseColor("#70000000"));
        canvas.drawRect(0, 0, getWidth(),
                getHeight() - getHeight() * progress / 100, mPaint);

        // 已完成區域:全透明,等於放行原圖
        mPaint.setColor(Color.parseColor("#00000000"));
        canvas.drawRect(0, getHeight() - getHeight() * progress / 100,
                getWidth(), getHeight(), mPaint);

        // 居中繪製百分比文字
        mPaint.setTextSize(30);
        mPaint.setColor(Color.parseColor("#FFFFFF"));
        mPaint.setStrokeWidth(2);
        Rect rect = new Rect();
        mPaint.getTextBounds("100%", 0, "100%".length(), rect); // 先量出文字寬度
        canvas.drawText(progress + "%",
                getWidth() / 2 - rect.width() / 2, getHeight() / 2, mPaint);
    }

    /** 更新進度並刷新界面 */
    public void setProgress(int progress) {
        this.progress = progress;
        postInvalidate();
    }
}

有幾個細節值得留意:setAntiAlias(true) 讓邊緣更平滑;getTextBounds 先量出「100%」的寬度,百分比才能嚴格水平居中;setProgress() 裡刻意選用 postInvalidate() 而非 invalidate(),這樣即使在子線程中更新進度也能安全地從消息隊列投遞重繪請求。

三、寫入佈局文件

把控件放進 activity_main.xml,注意此處必須寫全類名:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.processimageview.MainActivity">

    <com.example.processimageview.ProcessImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true"
        android:contentDescription="This is a ProcessImage"
        android:src="@drawable/image" />

</RelativeLayout>

四、驅動進度變化

最後在 MainActivity 中啟動一個子線程模擬上傳過程,每 200 毫秒進度加一,走滿後提示「圖片上傳完成」並隱藏遮罩:

package com.example.processimageview;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int SUCCESS = 0;

    private ProcessImageView processImageView;
    private int progress = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SUCCESS) {
                Toast.makeText(MainActivity.this, "圖片上傳完成", Toast.LENGTH_SHORT).show();
                processImageView.setVisibility(View.GONE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        processImageView = (ProcessImageView) findViewById(R.id.image);

        // 模擬圖片上傳
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (progress == 100) {
                        handler.sendEmptyMessage(SUCCESS);
                        return;
                    }
                    progress++;
                    processImageView.setProgress(progress);
                    try {
                        Thread.sleep(200);   // 暫停 0.2 秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

五、小結

編譯運行即可看到效果。整個控件不到一百行,沒有依賴任何第三方庫,卻能把「上傳中」這個狀態表達得非常直觀。真實項目裡,只要把 Thread.sleep 換成網路請求的實際回調,並在 onProgress 中調用 setProgress(),就能直接投入使用了。

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