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

再看本文的最終成果:

原理並不複雜:繼承 ImageView,在 onDraw 中先讓系統把原圖畫好,然後用畫筆覆蓋兩個矩形——「已完成」的區域用全透明色畫一筆,相當於什麼都不畫;「未完成」的區域用半透明黑色蓋住;最後在正中央補上百分比文字。進度每次變化時調用 postInvalidate() 觸發重繪即可。
新建 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(),就能直接投入使用了。
Android 文字與輸入指南:剪貼簿框架的复制與貼上實作
Android 提供強大的剪貼簿框架來實作複製與貼上。它支援從簡單字串到複雜資料結構、文字與二進位資料流,甚至是應用程式資產。簡單的文字直接存在剪貼簿裡,複雜的資料則以「
Android 座標系統入門:View 位置與觸控事件
Android 的座標系統以螢幕左上角為原點,向右為 X 軸正方向,向下為 Y 軸正方向。理解座標系統,是處理 View 位置、動畫與觸控事件的基礎。 View 的相對座
android 命令怎麼用:命令行下的 Android SDK 工具速查
Windows 用戶習慣了圖形界面的便利,但命令行才是圖形界面的根基。很多在 IDE 裡要點好幾層菜單的事情,一行命令就能搞定,值得花點時間熟悉。 進入 tools 目錄
Android 小工具實作:打造簡易隨機器與隨機數生成器
前言這是一個以 Android Studio 完成的簡易隨機器練習。它包含兩種模式:一種是輸入姓名後隨機抽取對象,另一種是設定最大值後產生隨機數。整個專案也示範了選單跳轉