通过给定的Mask来确定显示图片的形状
直接贴上代码
/**
* @author Momo
* */
public class XCRoundImageView extends ImageView {
private Paint paint;
public XCRoundImageView(Context context) {
this(context, null);
}
public XCRoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public XCRoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (null != drawable) {
//获得原始image
Bitmap src = ((BitmapDrawable) drawable).getBitmap();
//创建矩阵来放大或者缩小原始图片
//postScale(<这里面为放大或者缩小的参数>)
Matrix matrix = new Matrix();
float srcLength = pxTodp(Math.min(src.getWidth(),src.getHeight()));
matrix.postScale(1 / (srcLength / 44), 1 / (srcLength / 44));
//获得mask
//quick_settings_personal_center_mask -->这里是mask的资源文件
Bitmap mask = BitmapFactory.decodeResource(getResources(),R.drawable.quick_settings_personal_center_mask);
//创建符合要求大小的原始图片
Bitmap bitmap = Bitmap.createBitmap(((BitmapDrawable) drawable).getBitmap(), 0, 0, src.getWidth(),src.getHeight(),matrix,true);
//设置层级
int sr = canvas.saveLayer(0, 0, src.getWidth(),src.getHeight(), null, Canvas.ALL_SAVE_FLAG);
canvas.drawBitmap(bitmap,0,0,paint);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
canvas.restoreToCount(sr);
} else {
super.onDraw(canvas);
}
}
public int pxTodp(float px){
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}