import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.util.AttributeSet; import android.widget.ImageView; /** * 圓形背景ImageView */ public class CircleImageView extends ImageView { private BitmapShader bitmapShader = null; private Bitmap bitmap = null; private ShapeDrawable shapeDrawable = null; private int width = 0; private int height = 0; public CircleImageView(Context context) { super(context); } public CircleImageView(Context context, AttributeSet attrs) { super(context, attrs); } public CircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { width = getWidth(); height = getHeight(); bitmap = ((BitmapDrawable) getDrawable()).getBitmap(); // 從新生成指定大小的圖片 bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true); // 構造渲染器BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR, Shader.TileMode.REPEAT); // 將圖片裁剪爲橢圓形 // 構建ShapeDrawable對象並定義形狀爲橢圓 shapeDrawable = new ShapeDrawable(new OvalShape()); // 獲得畫筆並設置渲染器 shapeDrawable.getPaint().setShader(bitmapShader); // 設置顯示區域 shapeDrawable.setBounds(0, 0, width, height); // 繪製shapeDrawable shapeDrawable.draw(canvas); } }