當系統控件無法滿足獨特的視覺效果或交互邏輯時,自繪控件是 Android UI 開發的核心技能。通過繼承 View 並重寫核心方法,可實現任意複雜的圖形繪製、觸摸交互與動畫效果。本文從原理到實戰,構建自繪控件完整知識體系。
public class View extends Object implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
// 核心繪製流程:measure -> layout -> draw
// 關鍵回調方法:
// onMeasure(int widthMeasureSpec, int heightMeasureSpec) - 測量尺寸
// onLayout(boolean changed, int l, int t, int r, int b) - 確定位置 (ViewGroup 專用)
// onDraw(Canvas canvas) - 繪製內容
// onTouchEvent(MotionEvent event) - 觸摸交互
// onKeyDown/Up(int keyCode, KeyEvent event) - 按鍵事件
}
public class CustomView extends View {
// 必須實現的三個構造器(支持 XML 屬性、Style、預覽)
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
// 1. 解析自定義屬性
// 2. 初始化 Paint、Path、Bitmap 等繪圖對象
// 3. 註冊監聽器、啟動動畫等
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 1. 解析測量模式:EXACTLY/AT_MOST/UNSPECIFIED
// 2. 計算期望寬高
// 3. setMeasuredDimension(resolvedWidth, resolvedHeight)
super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 或自定義邏輯
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 核心繪製邏輯:canvas.drawXxx() 系列方法
// 例如:canvas.drawCircle(cx, cy, radius, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 處理觸摸事件:DOWN/MOVE/UP/CANCEL
// 返回 true 表示消費事件
return super.onTouchEvent(event);
}
// 提供外部調用的刷新方法
public void updateData(Data data) {
this.data = data;
invalidate(); // 請求重繪(主線程)
// 或 postInvalidate() // 非主線程
}
}
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗鋸齒
paint.setColor(Color.RED); // 顏色
paint.setStyle(Paint.Style.FILL); // FILL/STROKE/FILL_AND_STROKE
paint.setStrokeWidth(4f); // 描邊寬度
paint.setTextSize(32f); // 字體大小
paint.setTypeface(Typeface.DEFAULT_BOLD); // 字體
paint.setShader(new LinearGradient(...)); // 漸變著色器
paint.setShadowLayer(radius, dx, dy, color); // 陰影
paint.setPathEffect(new DashPathEffect(...)); // 路徑效果(虛線等)
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // 混合模式(圓角、遮罩)
public class CircleProgressBar extends View {
private Paint bgPaint, progressPaint, textPaint;
private RectF ovalRect = new RectF();
private float progress = 0f; // 0~1
private int progressColor = Color.BLUE;
private int bgColor = Color.LTGRAY;
public CircleProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
initPaints();
}
private void initPaints() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.STROKE);
bgPaint.setStrokeWidth(20f);
bgPaint.setColor(bgColor);
progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
progressPaint.setStyle(Paint.Style.STROKE);
progressPaint.setStrokeWidth(20f);
progressPaint.setColor(progressColor);
progressPaint.setStrokeCap(Paint.Cap.ROUND); // 圓角線帽
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(48f);
textPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int size = Math.min(measureDimension(200, widthMeasureSpec),
measureDimension(200, heightMeasureSpec));
setMeasuredDimension(size, size);
}
private int measureDimension(int defaultSize, int measureSpec) {
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
return mode == MeasureSpec.EXACTLY ? size : defaultSize;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int padding = 20; // 線寬一半
ovalRect.set(padding, padding, w - padding, h - padding);
}
@Override
protected void onDraw(Canvas canvas) {
// 1. 繪製背景圓環
canvas.drawOval(ovalRect, bgPaint);
// 2. 繪製進度弧線 (-90° 為起點,順時針)
float sweepAngle = 360 * progress;
canvas.drawArc(ovalRect, -90, sweepAngle, false, progressPaint);
// 3. 繪製中心百分比文字
String text = String.format(Locale.getDefault(), "%d%%", (int)(progress * 100));
Paint.FontMetrics fm = textPaint.getFontMetrics();
float textY = ovalRect.centerY() - (fm.ascent + fm.descent) / 2;
canvas.drawText(text, ovalRect.centerX(), textY, textPaint);
}
public void setProgress(float progress) {
this.progress = Math.max(0f, Math.min(1f, progress));
invalidate();
}
// 支持動畫驅動
public void setProgressWithAnimation(float targetProgress, int duration) {
ValueAnimator animator = ValueAnimator.ofFloat(this.progress, targetProgress);
animator.setDuration(duration);
animator.addUpdateListener(animation -> {
setProgress((float) animation.getAnimatedValue());
});
animator.start();
}
}
init 中創建,嚴禁在 onDraw 中 new 對象clipRect 限制繪製區域,避免繪製不可見內容setLayerType(LAYER_TYPE_SOFTWARE, null)BitmapRegionDecoder 按需解碼Canvas() 組合項替代自定義 View,狀態驅動重組自繪控件是 Android 圖形系統的皇冠上的明珠,掌握 Canvas-Paint-Path 鐵三角與 measure-layout-draw 生命週期,配合屬性動畫、觸摸事件分發機制,能創造出極致流暢、視覺震撼的自定義交互體驗。