自定义View圆形头像

public class CircleView extends android.support.v7.widget.AppCompatImageView {
    private int radius;
    public CircleView(Context context) {
        super(context);
    }
    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        radius = Math.min(measuredHeight, measuredWidth)/2;
    }
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
    @Override
    protected void onDraw(Canvas canvas) {

        Paint paint = new Paint();
        float mScale = 1;
        paint.setColor(getResources().getColor(R.color.colorAccent));
        BitmapDrawable drawable = (BitmapDrawable) getDrawable();
        if (drawable!=null) {
            Bitmap bitmap = drawable.getBitmap();
            BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            mScale = (radius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());
            Matrix matrix = new Matrix();
            matrix.setScale(mScale, mScale);
            bitmapShader.setLocalMatrix(matrix);
            paint.setShader(bitmapShader);
            canvas.drawCircle(radius,radius,radius,paint);
        } else {
            super.onDraw(canvas);
        }
    }

你可能感兴趣的:(自定义View圆形头像)