自定义view圆形头像

package com.example.zhidingyi;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

public class ZhiDingYi extends AppCompatImageView {

private int mins;
public ZhiDingYi(Context context) {
    super(context);
}

public ZhiDingYi(Context context, AttributeSet attrs) {
    super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int measuredHeight = getMeasuredHeight();
    int measuredWidth = getMeasuredWidth();
    mins = 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 = (mins*2.0f)/Math.min(bitmap.getHeight(), bitmap.getWidth());
        Matrix matrix = new Matrix();
        matrix.setScale(mScale, mScale);
        bitmapShader.setLocalMatrix(matrix);
        paint.setShader(bitmapShader);
        canvas.drawCircle(mins, mins, mins, paint);
    } else {
        super.onDraw(canvas);
    }
}

}

猜你喜欢

转载自blog.csdn.net/weixin_43875531/article/details/87880262