Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 BitmapShader 做出圓形與圓角圖片:原理與完整實作

編輯:關於 Android 程式設計

BitmapShader 是什麼

建構子長這樣:

public BitmapShader(Bitmap bitmap, Shader.TileMode tileX, Shader.TileMode tileY)

它產生一個「以指定 Bitmap 作為填色內容」的著色器(Shader)。參數中,tileX/tileY 決定當繪製區域超出圖片邊界時的填補方式。

TileMode 有三種:

CLAMP:超出原圖範圍時,重複使用邊緣像素向外延伸。

REPEAT:橫向與縱向平鋪重複。

MIRROR:以鏡像方式平鋪重複。

做圓形與圓角時一律用 CLAMP。但這裡有個疑問:若 View 的寬高比 Bitmap 大,圖片豈不是被拉伸?不會——我們會為 Shader 設定一個 Matrix,依比例放大或縮小圖片,確保永遠填滿整個 View。

整體流程:Drawable 轉 Bitmap → 建立 BitmapShader → 設定給 Paint → 在 onDraw 畫圓或圓角矩形。

一、自訂屬性

<attr name="borderRadius" format="dimension" />
<attr name="type">
    <enum name="circle" value="0" />
    <enum name="round" value="1" />
</attr>

<declare-styleable name="RoundImageView">
    <attr name="borderRadius" />
    <attr name="type" />
</declare-styleable>

二、讀取屬性與成員宣告

public class RoundImageView extends ImageView {

    /** 圖片類型:圓形或圓角 */
    private int type;
    private static final int TYPE_CIRCLE = 0;
    private static final int TYPE_ROUND = 1;

    /** 圓角預設值 10dp */
    private static final int BODER_RADIUS_DEFAULT = 10;
    private int mBorderRadius;
    private int mRadius;

    private Paint mBitmapPaint;
    private Matrix mMatrix;
    private BitmapShader mBitmapShader;
    private int mWidth;
    private RectF mRoundRect;

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mMatrix = new Matrix();
        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);

        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.RoundImageView);
        mBorderRadius = a.getDimensionPixelSize(
                R.styleable.RoundImageView_borderRadius,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                        BODER_RADIUS_DEFAULT, getResources().getDisplayMetrics()));
        type = a.getInt(R.styleable.RoundImageView_type, TYPE_CIRCLE);
        a.recycle();
    }
}

三、onMeasure:圓形強制等寬高

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (type == TYPE_CIRCLE) {
        mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
        mRadius = mWidth / 2;
        setMeasuredDimension(mWidth, mWidth);
    }
}

四、建立 BitmapShader

private void setUpShader() {
    Drawable drawable = getDrawable();
    if (drawable == null) {
        return;
    }

    Bitmap bmp = drawableToBitamp(drawable);
    mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP);

    float scale = 1.0f;
    if (type == TYPE_CIRCLE) {
        // 取寬高中的小值為基準,大值會導致填不滿
        int bSize = Math.min(bmp.getWidth(), bmp.getHeight());
        scale = mWidth * 1.0f / bSize;
    } else if (type == TYPE_ROUND) {
        // 取大值,確保縮放後一定大於 View(類似 centerCrop)
        scale = Math.max(getWidth() * 1.0f / bmp.getWidth(),
                         getHeight() * 1.0f / bmp.getHeight());
    }

    mMatrix.setScale(scale, scale);
    mBitmapShader.setLocalMatrix(mMatrix);
    mBitmapPaint.setShader(mBitmapShader);
}

/** Drawable 轉 Bitmap */
private Bitmap drawableToBitamp(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }
    int w = drawable.getIntrinsicWidth();
    int h = drawable.getIntrinsicHeight();
    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, w, h);
    drawable.draw(canvas);
    return bitmap;
}

scale 的計算邏輯值得細看:

圓形時取「小值」為基準。若用大值,縮放後會有一邊填不滿圓形區域。

圓角時取兩個比例的「大值」。因為要保證縮放後的圖片同時大於 View 的寬與高,才不會出現空白,這與 CenterCrop 的思路一致。舉例:View 為 10×20、圖片為 5×100,就該按寬的比例放大,而不是按高的比例縮小。

五、繪製

@Override
protected void onDraw(Canvas canvas) {
    if (getDrawable() == null) {
        return;
    }
    setUpShader();

    if (type == TYPE_ROUND) {
        canvas.drawRoundRect(mRoundRect, mBorderRadius, mBorderRadius, mBitmapPaint);
    } else {
        canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint);
    }
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if (type == TYPE_ROUND) {
        mRoundRect = new RectF(0, 0, getWidth(), getHeight());
    }
}

六、狀態保存與還原

若使用者旋轉螢幕,或 Activity 在背景被回收後重建,自訂 View 屬性會歸零。要保存「目前是圓形還是圓角、圓角多大」這類狀態,覆寫一對方法即可。

private static final String STATE_INSTANCE = "state_instance";
private static final String STATE_TYPE = "state_type";
private static final String STATE_BORDER_RADIUS = "state_border_radius";

@Override
protected Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState());
    bundle.putInt(STATE_TYPE, type);
    bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius);
    return bundle;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        super.onRestoreInstanceState(bundle.getParcelable(STATE_INSTANCE));
        this.type = bundle.getInt(STATE_TYPE);
        this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS);
    } else {
        super.onRestoreInstanceState(state);
    }
}

同時對外提供兩個動態修改的方法:

public void setBorderRadius(int borderRadius) {
    int pxVal = dp2px(borderRadius);
    if (this.mBorderRadius != pxVal) {
        this.mBorderRadius = pxVal;
        invalidate();
    }
}

public void setType(int type) {
    if (this.type != type) {
        this.type = type;
        if (this.type != TYPE_ROUND && this.type != TYPE_CIRCLE) {
            this.type = TYPE_CIRCLE;
        }
        requestLayout();   // 寬高可能改變,需重新測量
    }
}

public int dp2px(int dpVal) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal,
            getResources().getDisplayMetrics());
}

七、使用

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:zhy="https://schemas.android.com/apk/res/com.zhy.variousshapeimageview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.zhy.view.RoundImageView
            android:id="@+id/id_qiqiu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:src="@drawable/qiqiu" />

        <com.zhy.view.RoundImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_margin="10dp"
            android:src="@drawable/aa" />

        <com.zhy.view.RoundImageView
            android:id="@+id/id_meinv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:src="@drawable/aa"
            zhy:borderRadius="20dp"
            zhy:type="round" />

        <com.zhy.view.RoundImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:src="@drawable/icon"
            zhy:borderRadius="40dp"
            zhy:type="round" />
    </LinearLayout>
</ScrollView>
public class MainActivity extends Activity {

    private RoundImageView mQiQiu;
    private RoundImageView mMeiNv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mQiQiu = (RoundImageView) findViewById(R.id.id_qiqiu);
        mMeiNv = (RoundImageView) findViewById(R.id.id_meinv);

        mQiQiu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mQiQiu.setType(RoundImageView.TYPE_ROUND);
            }
        });

        mMeiNv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mMeiNv.setBorderRadius(90);
            }
        });
    }
}

兩個效能提醒

範例在 onDraw 中每次都呼叫 setUpShader(),這會在每次重繪時重新建立 Bitmap 與 Shader 物件,造成不必要的記憶體配置與 GC 壓力。實務上應該只在 onSizeChanged 或 setImageDrawable 之後重建 Shader,並快取下來重複使用。

另外,若圖片來源確定是本地 Bitmap,直接呼叫 drawableToBitamp 的 BitmapDrawable 分支即可,不必走 Canvas 重繪那條路;而後者產生的 Bitmap 記得在使用完畢後 recycle(),避免大圖造成 OOM。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved