简单的圆形头像

package com.bwie.test;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.graphics.Region;


public class CircleImageView extends ImageView{


private PaintFlagsDrawFilter mpaintFlagsDrawFilter;//毛边过滤
Paint paint;
Path path;




public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}


public CircleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}


public CircleImageView(Context context) {
super(context);
init();
}

//Path类可以预先在View上将N个点连成一条"路径",然后调用Canvas的drawPath(path,paint)即可沿着路径绘制图形
private void init() {
mpaintFlagsDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
// paint.setColor(Color.RED);

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(150, 150);
}

@Override
protected void onDraw(Canvas canvas) {
//View的高宽
float h = getMeasuredHeight()-3.0f;
float w = getMeasuredWidth()-3.0f;
if(path==null){
path = new Path();
path.addCircle(w/2.0f,h/2.0f, (float)Math.min(w/2.0f, h/2.0f), Path.Direction.CCW);
path.close();
}
// Math.min(w/2.0f, h/2.0f)+1.f
canvas.drawCircle(w/2.0f, h/2.0f,50, paint);
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.setDrawFilter(mpaintFlagsDrawFilter);
canvas.clipPath(path,Region.Op.REPLACE);
canvas.setDrawFilter(mpaintFlagsDrawFilter);
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
canvas.restoreToCount(saveCount);
}

}

你可能感兴趣的:(简单的圆形头像)