編輯:Android 開發實例
最近接到一個視覺需求:要在 ImageView 上疊一層半透明圓弧,並讓文字沿著弧線排布。最自然的做法是自訂一個 ImageView,在 onDraw() 裡把圓弧與文字畫上去。為了讓它能重複使用,圓弧的位置、顏色、透明度、線寬以及文字大小與顏色都開成了自訂屬性。

核心只有兩件事:用 Paint 畫弧,再用 Path 沿著同一條弧線畫文字。圓心位置由 drawStyle 決定,支援左上、左下、右上、右下與正中央五種擺法,你也可以自行擴充。程式中的預設值常數可依專案需求填入實際數字。
package com.chunk.customviewsdemo.views.ArcImageView;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.chunk.customviewsdemo.R;
/**
* 在 ImageView 上繪製圓弧與沿弧文字
*/
public class ArcImageView extends ImageView {
/** 文字預設大小 */
private final float DEFAULT_TEXT_SIZE = 20;
/** 決定圓弧直徑的縮放比例 */
private final float DEFAULT_SCALE = 1.5f;
/** 圓弧預設透明度 */
private final int DEFAULT_ARC_ALPHA = 128;
/** 圓弧預設線寬 */
private final int DEFAULT_ARC_WIDTH = 8;
/** 圓弧起始角 */
private final int DEFAULT_START_ANGLE = 0;
/** 圓弧掃過的角度 */
private final int DEFAULT_SWEEP_ANGLE = 90;
/** 文字沿路徑的起始偏移 */
private final int DEFAULT_H_OFFSET = 0;
/** 文字相對路徑的垂直偏移,負值在上、正值在下 */
private final int DEFAULT_V_OFFSET = 0;
private Context mContext;
/** 沿弧顯示的文字 */
private String mDrawStr;
private float mTextSize = DEFAULT_TEXT_SIZE;
private float mScale = DEFAULT_SCALE;
private int mArcAlpha = DEFAULT_ARC_ALPHA;
private int mArcWidth = DEFAULT_ARC_WIDTH;
private int mStartAngle = DEFAULT_START_ANGLE;
private int mSweepAngle = DEFAULT_SWEEP_ANGLE;
private float mHOffset = DEFAULT_H_OFFSET;
private float mVOffset = DEFAULT_V_OFFSET;
/** 圓弧擺放位置:LEFT_TOP、LEFT_BOTTOM、RIGHT_TOP、RIGHT_BOTTOM、CENTER */
private int mDrawStyle;
private int mArcColor;
private int mTextColor;
public ArcImageView(Context context) {
super(context);
this.mContext = context;
}
public ArcImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
obtainAttributes(attrs);
}
public ArcImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
obtainAttributes(attrs);
}
/** 設定沿弧顯示的文字 */
public void setDrawStr(String drawStr) {
this.mDrawStr = drawStr;
invalidate();
}
/** 設定圓弧透明度 */
public void setArcAlpha(int mArcAlpha) {
this.mArcAlpha = mArcAlpha;
invalidate();
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 先畫圓弧
Paint arcPaint = new Paint();
arcPaint.setStrokeWidth(mArcWidth);
arcPaint.setStyle(Paint.Style.STROKE);
arcPaint.setColor(mArcColor);
arcPaint.setAlpha(mArcAlpha);
int width = getWidth();
int height = getHeight();
float radius;
if (width > height) {
radius = mScale * height;
} else {
radius = mScale * width;
}
RectF oval = new RectF();
int center_x = width;
int center_y = height;
switch (mDrawStyle) {
case 0: // LEFT_TOP
center_x = 0;
center_y = 0;
mStartAngle = 0;
mSweepAngle = 90;
break;
case 1: // LEFT_BOTTOM
center_x = 0;
center_y = height;
mStartAngle = 270;
mSweepAngle = 90;
break;
case 2: // RIGHT_TOP
center_x = width;
center_y = 0;
mStartAngle = 0;
mSweepAngle = 90;
break;
case 3: // RIGHT_BOTTOM
center_x = width;
center_y = height;
mStartAngle = 0;
mSweepAngle = 90;
break;
case 4: // CENTER
center_x = width / 2;
center_y = height / 2;
mStartAngle = 0;
mSweepAngle = 360;
break;
}
float left = center_x - radius;
float top = center_y - radius;
float right = center_x + radius;
float bottom = center_y + radius;
oval.set(left, top, right, bottom);
canvas.drawArc(oval, mStartAngle, mSweepAngle, false, arcPaint);
// 再沿同一條弧線畫文字
Paint textPaint = new Paint();
textPaint.setTextSize(mTextSize);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(mTextColor);
Path path = new Path();
path.addArc(oval, mStartAngle, mSweepAngle);
canvas.drawTextOnPath(mDrawStr, path, mHOffset, mVOffset, textPaint);
}
/** 讀取 attrs.xml 中定義的自訂屬性 */
private void obtainAttributes(AttributeSet attrs) {
TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.ArcImageView);
mDrawStr = ta.getString(R.styleable.ArcImageView_drawStr);
mTextSize = ta.getDimension(R.styleable.ArcImageView_textSize, DEFAULT_TEXT_SIZE);
mArcAlpha = ta.getInteger(R.styleable.ArcImageView_arcAlpha, DEFAULT_ARC_ALPHA);
mArcWidth = ta.getInteger(R.styleable.ArcImageView_arcWidth, DEFAULT_ARC_WIDTH);
mStartAngle = ta.getInteger(R.styleable.ArcImageView_startAngle, DEFAULT_START_ANGLE);
mSweepAngle = ta.getInteger(R.styleable.ArcImageView_sweepAngle, DEFAULT_SWEEP_ANGLE);
mHOffset = ta.getInteger(R.styleable.ArcImageView_hOffset, DEFAULT_H_OFFSET);
mVOffset = ta.getInteger(R.styleable.ArcImageView_vOffset, DEFAULT_V_OFFSET);
mArcColor = ta.getColor(R.styleable.ArcImageView_arcColor, 0xFFCCCCCC);
mTextColor = ta.getColor(R.styleable.ArcImageView_textColor, 0xFFFFFFFF);
mDrawStyle = ta.getInt(R.styleable.ArcImageView_drawStyle, 0);
ta.recycle();
}
}
在 values 資料夾下的 attrs.xml 建立 declare-styleable,drawStyle 用 enum 限定五種取值:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="ArcImageView"> <attr name="drawStr" format="string" /> <attr name="textSize" format="dimension" /> <attr name="arcAlpha" format="integer" /> <attr name="arcWidth" format="integer" /> <attr name="startAngle" format="integer" /> <attr name="sweepAngle" format="integer" /> <attr name="scale" format="float" /> <attr name="hOffset" format="float" /> <attr name="vOffset" format="float" /> <attr name="drawStyle" format="enum"> <enum name="LEFT_TOP" value="0" /> <enum name="LEFT_BOTTOM" value="1" /> <enum name="RIGHT_TOP" value="2" /> <enum name="RIGHT_BOTTOM" value="3" /> <enum name="CENTER" value="4" /> </attr> <attr name="arcColor" format="color" /> <attr name="textColor" format="color" /> </declare-styleable> </resources>
使用自訂屬性時,根節點必須先宣告命名空間 xmlns:custom="https://schemas.android.com/apk/res-auto",否則 custom: 開頭的屬性無法解析。四個樣本分別擺在四個角落,展示不同 drawStyle 的視覺差異。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:custom="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:orientation="vertical" > <Button android:id="@+id/btn_another_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="換一組" /> <LinearLayout android:layout_width="match_parent" android:layout_height="200dp" android:layout_weight="1" android:orientation="horizontal" > <RelativeLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" > <com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id="@+id/aiv_one" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/steak" custom:drawStyle="RIGHT_BOTTOM" custom:drawStr="牛排" custom:arcAlpha="128" custom:arcColor="@color/gray" custom:textColor="@color/black" custom:textSize="16sp" /> </RelativeLayout> <RelativeLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" > <com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id="@+id/aiv_two" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/seafood" custom:drawStyle="LEFT_BOTTOM" custom:drawStr="海鮮" custom:arcAlpha="128" custom:arcColor="@color/gray" custom:textColor="@color/black" custom:textSize="16sp" /> </RelativeLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="200dp" android:layout_weight="1" android:orientation="horizontal" > <RelativeLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" > <com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id="@+id/aiv_three" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/cheese" custom:drawStyle="RIGHT_TOP" custom:drawStr="奶酪" custom:arcAlpha="128" custom:arcColor="@color/gray" custom:textColor="@color/black" custom:textSize="16sp" /> </RelativeLayout> <RelativeLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" > <com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id="@+id/aiv_four" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/barbecue" custom:drawStyle="LEFT_TOP" custom:drawStr="燒烤" custom:arcAlpha="128" custom:arcColor="@color/gray" custom:textColor="@color/black" custom:textSize="16sp" /> </RelativeLayout> </LinearLayout> </LinearLayout>
文字與背景都可以在執行期更換,只要呼叫 setDrawStr() 或 setBackgroundResource(),內部的 invalidate() 會觸發重繪。
package com.chunk.customviewsdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.chunk.customviewsdemo.views.ArcImageView.ArcImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArcImageView aiv_one;
private ArcImageView aiv_two;
private ArcImageView aiv_three;
private ArcImageView aiv_four;
private Button btn_another_one;
private int mGroup = 0;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aiv_one = (ArcImageView) findViewById(R.id.aiv_one);
aiv_one.setArcAlpha(128);
aiv_two = (ArcImageView) findViewById(R.id.aiv_two);
aiv_two.setArcAlpha(128);
aiv_three = (ArcImageView) findViewById(R.id.aiv_three);
aiv_three.setArcAlpha(128);
aiv_four = (ArcImageView) findViewById(R.id.aiv_four);
aiv_four.setArcAlpha(128);
btn_another_one = (Button) findViewById(R.id.btn_another_one);
btn_another_one.setOnClickListener(this);
}
@Override public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_another_one:
if (mGroup == 0) {
aiv_one.setDrawStr("蘋果");
aiv_one.setBackgroundResource(R.drawable.apple);
aiv_two.setDrawStr("柚子");
aiv_two.setBackgroundResource(R.drawable.pineapple);
aiv_three.setDrawStr("香蕉");
aiv_three.setBackgroundResource(R.drawable.banana);
aiv_four.setDrawStr("菠蘿");
aiv_four.setBackgroundResource(R.drawable.pineapple);
mGroup = 1;
} else {
aiv_one.setDrawStr("牛排");
aiv_one.setBackgroundResource(R.drawable.steak);
aiv_two.setDrawStr("海鮮");
aiv_two.setBackgroundResource(R.drawable.seafood);
aiv_three.setDrawStr("奶酪");
aiv_three.setBackgroundResource(R.drawable.cheese);
aiv_four.setDrawStr("燒烤");
aiv_four.setBackgroundResource(R.drawable.barbecue);
mGroup = 0;
}
break;
}
}
}
實際跑起來的樣子:

小結一下:自訂 View 的套路其實很固定,覆寫 onDraw、onMeasure、onLayout 等方法完成量測與繪製,繪製時少不了 Canvas、Paint、Path、Bitmap 這幾個角色。這個過程本質上就是把現實中的畫板、畫紙、畫筆抽象成物件,再透過組合與呼叫完成作畫。若對 2D 繪圖 API 還不夠熟悉,建議補讀 Canvas 與 Path 的官方文件,會比直接抄程式碼收穫更多。
Android 手勢(Gesture)處理:從單擊、滑動到多點縮放
觸控螢幕上的操作千變萬化,Android 把幾種常見的動作抽象成「手勢」:點擊、長按、滑動、快速滑動(Fling)、雙指捏合縮放等。應用程式只要攔截這些手勢,就能提供更自
仿優酷 App 圖片輪播:ViewPager 自動切換完整實作
這個範例用 ViewPager 實作了圖片輪播,同時支援自動播放與手動滑動。其實不只優酷,許多商城與入口網站的首頁 banner 都是同一套邏輯。實作思路1. 加入 su
Android 進度條實作:用 Loading Spinner 表示「還不知道要等多久」
Android 的 ProgressBar 有兩種常見形態:一種是帶有百分比的進度條(progress bar),另一種是持續旋轉的轉圈動畫,也就是本章的主角 Spinn
Android 登入畫面實作:帳密驗證與錯誤次數限制
幾乎每個需要使用者帳號的 App 都少不了一個登入畫面,無論是自家服務還是 Facebook、微博這類第三方平台。本章要說明如何打造一個登入介面,並處理最容易被忽略的兩件