編輯:關於 Android 程式設計
建構子長這樣:
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();
}
}
@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);
}
}
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。
Android Studio 1.5.1 配置 NDK 開發:JNI 入門全流程與踩坑記錄
要在 Android 裡跑 C/C++ 代碼,NDK 是必經之路。這篇記錄在 Android Studio 1.5.1 上配置 NDK 並完成第一個 JNI 程序的完整過
Android 裡那些容易被忽略的 UI 細節:從游標、滾動條到點九圖
做 Android 專案久了會發現,真正拉開產品質感差距的往往不是什麼高階架構,而是一堆不起眼的細節:輸入框游標的顏色、選字時那個小水滴手柄、滾動條的粗細與位置、滑到底部
Android 滑動機制全解析:從座標系到七種位移實作
重點導覽 本文重新整理 Android 滑動效果的核心概念,從座標系、觸控事件到七種常見位移方式,幫助讀者建立完整的實作脈絡。 一、滑動效果如何產生 所謂滑動,本質上是根
用原生 GridView 做一個九宮格功能頁
需求背景 新專案有個頁面要做成九宮格:每個 Item 上方一張圖片、下方一行文字說明,點擊後跳到對應的功能頁。與其去找第三方庫,不如直接用 Android 原生的 Gri