[譯]Android:自定義Drawable教程

#這篇教程一共分為三個(gè)部分。

1 Drawable與View

Drawable是什么?API文檔的定義:A Drawable is a general abstraction for "something that can be drawn."。就是說(shuō)Drawable表示這類可以被繪制的事物。
那么,如何使用,怎么把它添加到View上?我們來(lái)一步一步回答這個(gè)問(wèn)題。
現(xiàn)在,我們有個(gè)需求,給圖片添加邊框,效果如下,

border imageview

BorderDrawable

首先,我們創(chuàng)建一個(gè)Drawable的子類,并創(chuàng)建帶參的構(gòu)造器。

public class BorderDrawable extends Drawable {
    Paint mPaint;
    int mColor;
    int mBorderWidth;
    int mBorderRadius;
    RectF mRect;
    Path mPath;

    public BorderDrawable(int color, int borderWidth, int borderRadius) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);

        mPath = new Path();
        mPath.setFillType(Path.FillType.EVEN_ODD);

        mRect = new RectF();

        mColor = color;
        mBorderWidth = borderWidth;
        mBorderRadius = borderRadius;
    }
}

onBoundsChange(Rect)的時(shí)候計(jì)算mPath;
draw(Canvas)繪制mPath。

@Override protected void onBoundsChange(Rect bounds) {
    mPath.reset();

    mPath.addRect(bounds.left, bounds.top, bounds.right, bounds.bottom, Path.Direction.CW);
    mRect.set(bounds.left + mBorderWidth, bounds.top + mBorderWidth, bounds.right - mBorderWidth, bounds.bottom - mBorderWidth);
    mPath.addRoundRect(mRect, mBorderRadius, mBorderRadius, Path.Direction.CW);
}

@Override public void draw(Canvas canvas) {
    mPaint.setColor(mColor);
    canvas.drawPath(mPath, mPaint);
}

@Override public void setAlpha(int alpha) {
    mPaint.setAlpha(alpha);
}

@Override public void setColorFilter(ColorFilter cf) {
    mPaint.setColorFilter(cf);
}

@Override public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}

BorderImageView

然后處理ImageView,

public class BorderImageView extends ImageView {

    BorderDrawable mBorder;

    public BorderImageView(Context context) {
        super(context);

        init(context, null, 0, 0);
    }

    public BorderImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context, attrs, 0, 0);
    }

    //another constructors ...
    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        setWillNotDraw(false);
        mBorder = new BorderDrawable(context.getResources().getColor(R.color.primary), getPaddingLeft(), getPaddingLeft() / 2);
    }

}

上面調(diào)用setWillNotDraw(false)傳入了false,保證自定義View會(huì)執(zhí)行onDraw(canvas),否則不會(huì)執(zhí)行。然后把ImageView的padding 值當(dāng)作border的寬度。
然后重寫(xiě)onSizeChanged(int, int, int, int),設(shè)置drawable的尺寸。

@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBorder.setBounds(0, 0, w, h);
}

然后在onDraw(canvas)里調(diào)用drawable的draw(Canvas)

Override protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mBorder.draw(canvas);
}

最后,

<com.rey.tutorial.widget.BorderImageView
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/avatar"
    android:scaleType="centerCrop"
    android:padding="8dp"/>

其實(shí),可以直接在ImageView 的onDraw(Canvas)里繪制邊框,但是使用drawable便于復(fù)用。

2-創(chuàng)建帶狀態(tài)的drawable

現(xiàn)在,新需求來(lái)了,點(diǎn)擊View邊框顏色改變,效果如下,


state-based

StateBorderDrawable

我們來(lái)改寫(xiě)B(tài)orderDrawable。
首先,把int color參數(shù)改成ColorStateList 。

public class StateBorderDrawable extends Drawable {

    Paint mPaint;
    ColorStateList mColorStateList;
    int mColor;
    int mBorderWidth;
    int mBorderRadius;

    RectF mRect;
    Path mPath;

    public BorderDrawable(ColorStateList colorStateList, int borderWidth, int borderRadius) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);

        mPath = new Path();
        mPath.setFillType(Path.FillType.EVEN_ODD);

        mRect = new RectF();

        mColorStateList = colorStateList;
        mColor = mColorStateList.getDefaultColor();
        mBorderWidth = borderWidth;
        mBorderRadius = borderRadius;
    }
}

isStateful()返回true,表明當(dāng)view的狀態(tài)改變的時(shí)候會(huì)通知這個(gè)Drawable。在onStateChange(int)方法里處理狀態(tài)改變事件。

@Override
public boolean isStateful() {
    return true;
}

@Override
protected boolean onStateChange(int[] state) {
    int color = mColorStateList.getColorForState(state, mColor);
    if(mColor != color){
        mColor = color;
        invalidateSelf();
        return true;
    }

    return false;
}

如果當(dāng)前drawable的顏色與view當(dāng)前狀態(tài)對(duì)應(yīng)的顏色不一樣,調(diào)用invalidateSelf()重新繪制。

StateBorderImageView

改寫(xiě)B(tài)orderImageView。
首先,init()方法:

private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
    setWillNotDraw(false);
    int[][] states = new int[][]{
            {-android.R.attr.state_pressed},
            {android.R.attr.state_pressed}
    };
    int[] colors = new int[]{
            context.getResources().getColor(R.color.primary),
            context.getResources().getColor(R.color.accent)
    };
    ColorStateList colorStateList = new ColorStateList(states, colors);

    mBorder = new StateBorderDrawable(colorStateList, getPaddingLeft(), getPaddingLeft() / 2);
    mBorder.setCallback(this);
}

Drawable對(duì)象必須調(diào)用setCallback(Callback),才保證Drawable狀態(tài)invalidated的時(shí)候,回調(diào)ImageView的重繪,進(jìn)而重繪Drawable。

@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();
    mBorder.setState(getDrawableState());
}
@Override
protected boolean verifyDrawable(Drawable dr) {
    return super.verifyDrawable(dr) || dr == mBorder;
}

drawableStateChanged()當(dāng)view狀態(tài)改變,這個(gè)方法去通知drawable。
verifyDrawable()當(dāng)drawable請(qǐng)求view重繪自己時(shí)(重繪是通過(guò)Callback的invalidateDrawable(Drawable)方法),view會(huì)先檢查這個(gè)drawable是不是屬于自己。

最后,

<com.rey.tutorial.widget.StateBorderImageView
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/avatar"
    android:scaleType="centerCrop"
    android:padding="8dp"/>

3-創(chuàng)建帶動(dòng)畫(huà)的drawable

現(xiàn)在,新需求,逃不過(guò)的動(dòng)畫(huà),


animated drawable

AnimatedStateBorderDrawable

來(lái)改寫(xiě)StateBorderDrawable。
首先,我們需要一個(gè)duration參數(shù)。

public class AnimatedStateBorderDrawable extends Drawable {

    private boolean mRunning = false;
    private long mStartTime;
    private int mAnimDuration;

    Paint mPaint;
    ColorStateList mColorStateList;
    int mPrevColor;
    int mMiddleColor;
    int mCurColor;
    int mBorderWidth;
    int mBorderRadius;

    RectF mRect;
    Path mPath;

    public BorderDrawable(ColorStateList colorStateList, int borderWidth, int borderRadius, int duration) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);

        mPath = new Path();
        mPath.setFillType(Path.FillType.EVEN_ODD);

        mRect = new RectF();

        mColorStateList = colorStateList;
        mCurColor = mColorStateList.getDefaultColor();
        mPrevColor = mCurColor;
        mBorderWidth = borderWidth;
        mBorderRadius = borderRadius;
        mAnimDuration = duration;
    }
}

添加了一些新變量,比如mPrevColor,mCurColor,mMiddeColor。需要知道之前和當(dāng)前狀態(tài)的顏色值,才能在兩個(gè)狀態(tài)之間添加顏色動(dòng)畫(huà)。變量mRunning,mStartTime為了記錄動(dòng)畫(huà)數(shù)據(jù)。
然后實(shí)現(xiàn)android.graphics.drawable.Animatable接口,重寫(xiě)3個(gè)方法。

@Override
public boolean isRunning() {
    return mRunning;
}

@Override
public void start() {
    resetAnimation();
    scheduleSelf(mUpdater, SystemClock.uptimeMillis() + FRAME_DURATION);
    invalidateSelf();
}

@Override
public void stop() {
    mRunning = false;
    unscheduleSelf(mUpdater);
    invalidateSelf();
}

調(diào)用start()開(kāi)始動(dòng)畫(huà)。3行代碼干3件事。
先重置動(dòng)畫(huà)數(shù)據(jù),mStartTime記錄動(dòng)畫(huà)開(kāi)始時(shí)間,mMiddleColor記錄動(dòng)畫(huà)執(zhí)行過(guò)程中繪制的顏色。
然后scheduleSelf ()方法,將在指定的時(shí)間執(zhí)行第一個(gè)參數(shù)Runnable。
invalidateSelf()使Drawable狀態(tài)invalidated,這會(huì)通知Callback。

private void resetAnimation(){
    mStartTime = SystemClock.uptimeMillis();
    mMiddleColor = mPrevColor;
}

private final Runnable mUpdater = new Runnable() {

    @Override
    public void run() {
        update();
    }

};

private void update(){
    long curTime = SystemClock.uptimeMillis();
    float progress = Math.min(1f, (float) (curTime - mStartTime) / mAnimDuration);
    mMiddleColor = getMiddleColor(mPrevColor, mCurColor, progress);

    if(progress == 1f)
        mRunning = false;

    if(isRunning())
        scheduleSelf(mUpdater, SystemClock.uptimeMillis() + FRAME_DURATION);

    invalidateSelf();
}

update()方法,通過(guò)動(dòng)畫(huà)進(jìn)度和兩個(gè)狀態(tài)顏色值計(jì)算mMiddleColor,然后根據(jù)動(dòng)畫(huà)是否執(zhí)行完畢來(lái)決定是否繼續(xù)安排任務(wù)mUpdater

@Override
protected boolean onStateChange(int[] state) {
    int color = mColorStateList.getColorForState(state, mCurColor);

    if(mCurColor != color){
        if(mAnimDuration > 0){
            mPrevColor = isRunning() ? mMiddleColor : mCurColor;
            mCurColor = color;
            start();
        }
        else{
            mPrevColor = color;
            mCurColor = color;
            invalidateSelf();
        }
         return true;
    }

    return false;
}

@Override
public void draw(Canvas canvas) {
    mPaint.setColor(isRunning() ? mMiddleColor : mCurColor);
    canvas.drawPath(mPath, mPaint);
}

@Override
public void jumpToCurrentState() {
    super.jumpToCurrentState();
    stop();
}

@Override
public void scheduleSelf(Runnable what, long when) {
    mRunning = true;
    super.scheduleSelf(what, when);
}

當(dāng)view想讓drawable無(wú)動(dòng)畫(huà)直接轉(zhuǎn)變狀態(tài)時(shí),jumpToCurrentState()會(huì)被調(diào)用,所以我們stop()動(dòng)畫(huà)。

AnimatedStateBorderImageView

改寫(xiě)StateBorderImageView.

mBorder = new AnimatedStateBorderDrawable(colorStateList, 
        getPaddingLeft(), 
        getPaddingLeft() / 2, 
        context.getResources().getInteger(android.R.integer.config_mediumAnimTime));

@Override
public void jumpDrawablesToCurrentState() {
    super.jumpDrawablesToCurrentState();
    mBorder.jumpToCurrentState();
}

jumpDrawablesToCurrentState()通知drawable狀態(tài)改變。

<com.rey.tutorial.widget.AnimatedStateBorderImageView
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/avatar"
    android:scaleType="centerCrop"
    android:padding="8dp"/>

相關(guān)代碼
https://github.com/rey5137/tutorials/tree/add_drawable_to_view
https://github.com/YoungPeanut/ApiDemos/blob/3bd9112f79bfa8a7ee006293913f947d6888514c/app/src/main/java/com/example/android/graphics/CircleDrawable.java

英文博客原文
https://medium.com/@rey5137/custom-drawable-part-3-b7adfd97d0b3

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容