XML直接可以引用
public class CircleImageDrawable extends Drawable {
private Paint mPaint;
private Bitmap mBitmap;
private int mWidth;
public CircleImageDrawable(Bitmap bitmap) {
mBitmap = bitmap;
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(shader);
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 i) {
mPaint.setAlpha(i);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
Activity里的引用
public class FirstActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
imageBtn = (ImageView) findViewById(R.id.imageBtn);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.headphoto);
imageBtn.setImageDrawable(new CircleImageDrawable(bitmap));
}
}