方法1
public class RoundImageView extends ImageView{ int width=0,height=0; //半径 int radius=0; Paint paint; BitmapShader shader; Matrix matrix; public RoundImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public RoundImageView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setAntiAlias(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = Math.min(getMeasuredWidth(), getMeasuredHeight()); radius = width/2; setMeasuredDimension(width, width); } @Override protected void onDraw(Canvas canvas) { if (getDrawable()==null) { return; } Bitmap bmp=null; if (getDrawable() instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) getDrawable(); bmp = bd.getBitmap(); } shader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP); float scale =1f; int size = Math.min(bmp.getWidth(), bmp.getHeight()); scale =width*1.0f/size; matrix = new Matrix(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); paint.setShader(shader); canvas.drawCircle(radius, radius, radius, paint); } }
方法2
public class RoundDrawable extends Drawable { private Paint mPaint; private int mWidth; private Bitmap mBitmap; public RoundDrawable(Bitmap bitmap) { mBitmap = bitmap; BitmapShader bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setShader(bitmapShader); mWidth = Math.min(mBitmap.getWidth(), mBitmap.getHeight()); } @Override public void draw(Canvas canvas) { canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, mPaint); } @Override public int getIntrinsicWidth() { return mWidth; } @Override public int getIntrinsicHeight() { return mWidth; } @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; } }