Android设置圆形的ImageView

    初学andorid 遇到一个圆形的ImageView显示的需求,网上已经有了很多方法,网上找过很多资料,用重写ImageView Ondraw()方法加上自己的理解,整理了一下:

1.新建一个Imageview类,继承AppCompatImageView
2.重写一个ondraw方法
3.在Canvas画布中对图片进行裁剪

由于之前没有java基础,纯属初学摸索,所以查了很多基本的方法和元素并且注释。如果有不对的地方希望大家一起指正:

public class drawImg extends AppCompatImageView {
//定义画笔,消除锯齿:Paint.ANTI_ALIAS_FLAG
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//定义位图
private Bitmap mbitmap;
//图片渲染器,是shader渲染的子类,主要是对图片进行渲染的
private BitmapShader bitmapShader;
//定义矩阵,可以对矩阵内的图片进行缩放,渲染,裁剪,拉伸等操作

public class drawImg extends AppCompatImageView {
//定义画笔,消除锯齿:Paint.ANTI_ALIAS_FLAG
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//定义位图
private Bitmap mbitmap;
//图片渲染器,是shader渲染的子类,主要是对图片进行渲染的
private BitmapShader bitmapShader;
//定义矩阵,可以对矩阵内的图片进行缩放,渲染,裁剪,拉伸等操作
private Matrix matrix = new Matrix();

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

@Override
protected void onDraw(Canvas canvas) {
    Bitmap nbitmap = getBitmap(getDrawable());
    if (nbitmap != null) {
        int viewwidth = getWidth();
        int viewhight = getHeight();
        int viewminsize = Math.min(viewwidth, viewhight);
        float destwidth = viewminsize;
        float desthight = viewminsize;
        if (bitmapShader == null || !nbitmap.equals(mbitmap)) {
            mbitmap = nbitmap;
            bitmapShader = new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        }
        if (bitmapShader != null) {
            matrix.setScale(destwidth / nbitmap.getWidth(), desthight / nbitmap.getHeight());
            bitmapShader.setLocalMatrix(matrix);
        }
        paint.setShader(bitmapShader);
        float radius = viewminsize / 2.0f;
        canvas.drawCircle(radius, radius, radius, paint);

    } else {

        super.onDraw(canvas);
    }

}

//新建图片获取方法
private Bitmap getBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof ColorDrawable) {
        // 获取边界
        Rect rect = drawable.getBounds();
        int width = rect.right- rect.left;
        int height = rect.bottom - rect.top;
        //获取图片颜色
        int color = ((ColorDrawable) drawable).getColor();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
        return bitmap;
    } else {
        return null;
    }

}

然后再layout布局文件中包名加控件名称,就OK了
Android设置圆形的ImageView_第1张图片
Android设置圆形的ImageView_第2张图片

你可能感兴趣的:(Android,studio)