前言
在網(wǎng)上看到一張圖,花了些時間自己嘗試著寫了一個自定義View,里面涉及到了自定義屬性、自定義View padding屬性的處理、畫筆(Paint)和畫布(Canvas)的使用、分辨率適配問題、性能問題、屬性動畫等,覺得還是有些東西值的記錄一下的,效果圖如下:

自定義屬性
基礎(chǔ)屬性定義說明:
| 屬性類型 | 屬性定義方式 | 屬性值說明 |
|---|---|---|
| color | <attr format="color" name="屬性名稱"/> | #FF565656 |
| string | <attr format="string" name="屬性名稱"/> | "字符串" |
| integer | <attr format="integer" name="屬性名稱"/> | 123 |
| boolean | <attr format="boolean" name="屬性名稱"/> | true |
| fraction | <attr format="fraction" name="屬性名稱"/> | 0.9 |
| reference | <attr format="reference" name="屬性名稱"/> | @drawable/text_color |
| dimension | <attr format="dimension" name="屬性名稱"/> | 23dp |
| enum | <attr format="enum" name="屬性名稱"> <enum name="horizontal" value="0"/> <enum name="vertical" value="1"/> </attr> |
自定義屬性的步驟如下:
1、在values目錄下創(chuàng)建一個attrs.xml文件。

2、在屬性文件attrs.xml中聲明屬性。
<declare-styleable name="CircleProgress">
<attr name="foreground_color" format="color"/>
<attr name="background_color" format="color"/>
<attr name="text_color" format="color"/>
<attr name="stroke_width" format="dimension"/>
</declare-styleable>
3、在布局文件中使用自定義屬性。
布局中使用自定義屬性(最后一行):
<com.android.peter.animationdemo.CircleProgress
android:id="@+id/cp_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/message"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:stroke_width="8dp"/>
在自定義View中使用這些屬性:
private void initTypedArray(Context context,AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.CircleProgress);
try {
mStrokeWidth = ta.getDimension(R.styleable.CircleProgress_stroke_width,getResources().getDimension(R.dimen.circle_progress_default_stroke_width));
mBackgroundColor = ta.getColor(R.styleable.CircleProgress_background_color,getResources().getColor(R.color.white,null));
mForegroundColor = ta.getColor(R.styleable.CircleProgress_foreground_color,getResources().getColor(R.color.colorPrimary,null));
mTitleTextColor = ta.getColor(R.styleable.CircleProgress_text_color,getResources().getColor(R.color.colorPrimary,null));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(ta != null) {
ta.recycle();
}
}
}
通過上述方式就可以在布局文件中定義這些屬性的值,在Class中讀取這些屬性值。如果,自定義屬性沒有被賦值就會使用預(yù)設(shè)的缺省值作為屬性值。這里有兩點需要注意:
1、TypedArray使用完一定要回收,否則會造成內(nèi)存泄漏。
2、屬性缺省值應(yīng)該在demens.xml文件中定義,不能只是傳遞一個數(shù)值。否則會導(dǎo)致在不同分辨率的手機上顯示大小不一致。
自定義View
自定義View需要重寫onMeasure、onLayout和onDraw三個方法,分別用來測量、定位和繪制。
1、在onMeasure方法中根據(jù)測量模式設(shè)置View默認(rèn)的寬高。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.i(TAG,"onMeasure");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if(widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension((int)getResources().getDimension(R.dimen.circle_progress_default_width),
(int)getResources().getDimension(R.dimen.circle_progress_default_height));
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension((int)getResources().getDimension(R.dimen.circle_progress_default_width), heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize,(int)getResources().getDimension(R.dimen.circle_progress_default_height));
}
}
2、在onLayout方法中對一些數(shù)據(jù)進(jìn)行處理。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Log.i(TAG,"onLayout");
super.onLayout(changed, left, top, right, bottom);
mPaddingStart = getPaddingStart() + (int)(mStrokeWidth/4);
mPaddingEnd = getPaddingEnd() + (int)(mStrokeWidth/4);
mPaddingTop = getPaddingTop() + (int)(mStrokeWidth/4);
mPaddingBottom = getPaddingBottom() + (int)(mStrokeWidth/4);
mViewWidth = getWidth() - mPaddingStart - mPaddingEnd;
mViewHeight = getHeight() - mPaddingTop - mPaddingBottom;
mCenterX = mPaddingStart + mViewWidth/2;
mCenterY = mPaddingTop + mViewHeight/2;
mCircleRadius = mViewWidth < mViewHeight ? mViewWidth/2 : mViewHeight/2;
mFrameRectF.set(mCenterX - mCircleRadius,
mCenterY - mCircleRadius,
mCenterX + mCircleRadius,
mCenterY + mCircleRadius);
}
3、在onDraw中進(jìn)行View的繪制。
@Override
protected void onDraw(Canvas canvas) {
Log.i(TAG,"onDraw");
super.onDraw(canvas);
// background
canvas.drawCircle(mCenterX,mCenterY,mCircleRadius - mStrokeWidth/2, mBackgroundPaint);
// foreground
canvas.drawArc(mFrameRectF.left + mStrokeWidth/2,mFrameRectF.top + mStrokeWidth/2,mFrameRectF.right - mStrokeWidth/2,
mFrameRectF.bottom - mStrokeWidth/2,270,(float) (3.6* mPercentage),false,mForegroundPaint);
// end circle
if(mPercentage != 0 && mPercentage != 100) {
// end out circle
canvas.drawCircle((float) (mCenterX + (mCircleRadius-mStrokeWidth/2)*Math.cos((3.6* mPercentage -90)*Math.PI/180)),
(float)(mCenterY + (mCircleRadius-mStrokeWidth/2)*Math.sin((3.6* mPercentage -90)*Math.PI/180)), mStrokeWidth*3/4, mEndOutCirclePaint);
// end inner circle
canvas.drawCircle((float) (mCenterX + (mCircleRadius-mStrokeWidth/2)*Math.cos((3.6* mPercentage -90)*Math.PI/180)),
(float)(mCenterY + (mCircleRadius-mStrokeWidth/2)*Math.sin((3.6* mPercentage -90)*Math.PI/180)), mStrokeWidth/4, mEndInnerCirclePaint);
}
// text
mTitleTextPaint.getTextBounds(mTitleText,0,mTitleText.length(), mTextRect);
canvas.drawText(mTitleText,mCenterX,mCenterY/2 + mTextRect.height()/2,mTitleTextPaint);
mValueTextPaint.getTextBounds(mValueText,0,mValueText.length(),mTextRect);
canvas.drawText(mValueText,mCenterX,mCenterY + mTextRect.height()/2,mValueTextPaint);
mUnitTextPaint.getTextBounds(mUnitText,0,mUnitText.length(),mTextRect);
canvas.drawText(mUnitText,mCenterX,mCenterY*4/3,mUnitTextPaint);
// coordinate
/*canvas.drawLine(0,mCenterY,2*mCenterX,mCenterY,mTestPaint);
canvas.drawLine(mCenterX,0,mCenterX,2*mCenterY,mTestPaint);*/
}
注意,在onDraw方法里面盡量不要新建對象和做耗時操作,因為onDraw經(jīng)常會被頻繁調(diào)用,新建對象會觸發(fā)垃圾回收導(dǎo)致內(nèi)存抖動影響性能。耗時操作會導(dǎo)致在一個繪制周期內(nèi)無法完成所有的繪制工作從而出現(xiàn)丟幀問題。
添加動畫效果
首先借助ValueAnimator類定義一個動畫,然后為這個動畫添加一個監(jiān)聽器監(jiān)聽動畫更新事件。每當(dāng)有事件更新就獲取animation的值并記錄下來,然后觸發(fā)view刷新,view刷新的時候就會重新onDraw從而根據(jù)記錄下來的值進(jìn)行重繪,這樣連續(xù)起來就實現(xiàn)了想要的動畫效果。 對之前的代碼重新封裝了一下,核心代碼如下。
在第一次觸發(fā)onDraw的時候啟動動畫。
@Override
protected void onDraw(Canvas canvas) {
Log.i(TAG,"onDraw");
super.onDraw(canvas);
if(mIsFirstTime) {
startCircleProgressAnim();
startValueAnim();
mIsFirstTime = false;
}
// background circle
drawBackgroundCircle(canvas);
// foreground circle
drawForegroundCircle(canvas);
// content
drawContent(canvas);
// coordinate
// drawCoordinate(canvas);
}
實現(xiàn)動畫及監(jiān)聽動畫更新的邏輯。
public void startCircleProgressAnim() {
ValueAnimator anim = ValueAnimator.ofInt(0, mPercent);
anim.setDuration(500);
anim.setInterpolator(new LinearInterpolator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mTempPercent = (int) animation.getAnimatedValue();
invalidate();
}
});
anim.start();
}
public void startValueAnim() {
ValueAnimator anim = ValueAnimator.ofInt(0, mValue);
anim.setDuration(500);
anim.setInterpolator(new LinearInterpolator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mTempValueText = Integer.toString((Integer) animation.getAnimatedValue());
invalidate();
}
});
anim.start();
}
小結(jié)
通過上述簡單步驟就可以實現(xiàn)一個帶動畫的自定義View,重要地方都做了加粗處理。在實現(xiàn)自定義View的時候主要耗時在繪制位置的計算上了。另外,Math的sin和cos方法使用的時候需要注意傳遞參數(shù)要用度數(shù)乘以Math.PI/180。文字居中繪制只需對畫筆進(jìn)行如下設(shè)置無需測量計算。
Paint.setTextAlign(Paint.Align.CENTER);
參考文獻(xiàn)
關(guān)于Android自定義屬性你可能不知道的細(xì)節(jié)
Android Canvas之Path操作
Property Animation(屬性動畫)使用詳解