圆角图片2 RoundedBitmapDrawable 加载本地图片

  • 参考博文

  1. Android 圆角图片的实现         ——矩形图片通过裁剪实现圆形图片
  2. Android圆角图片和圆形图片实现总结   ——多种圆角图片绘制方式

  3. android RoundedBitmapDrawable最简单方式实现圆角图片   ——RounedBitMapDrawable图片显示变形问题处理以及添加边框

  • 效果演示(引用其他博文效果,实测如下)

  

  • 核心代码

⭐矩形图片 ivRectImg.setImageDrawable(bitmapDrawable);

public static RoundedBitmapDrawable tranRoundBitmap(Context context,int drawableId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);
        RoundedBitmapDrawable bitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
        bitmapDrawable.setAntiAlias(true);
        bitmapDrawable.setCornerRadius(10); //控制圆角半径
//        ivRectImg.setImageDrawable(bitmapDrawable); //使用方法
        return bitmapDrawable;
}

圆形图片 Bitmap.createBitmap 变形图片的处理

private void circleBitmap() {
     Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_bg);
        Bitmap circle = null;
        int min = Math.min(width, height);
        int max = Math.max(width, height);
        if (width == height) {
            circle = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        } else {
            // 居中裁剪
            if (width > height) {
                circle = Bitmap.createBitmap(bitmap, (max - min) / 2, 0, min, min);
            } else {
                circle = Bitmap.createBitmap(bitmap, 0, (max - min) / 2, min, min);
            }
        }
        RoundedBitmapDrawable bitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), circle);
        bitmapDrawable.setCornerRadius(min / 2);
        bitmapDrawable.setAntiAlias(true);
        ivCircleImg.setImageDrawable(bitmapDrawable);
    }

圆形图片添加边框 drawCircle (圆角矩形不统用)

        Canvas canvas = new Canvas(roundedBitmap);
        Paint borderPaint = new Paint();
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(borderWidthHalf);
        borderPaint.setColor(Color.WHITE);
        //添加边框
        canvas.drawCircle(canvas.getWidth()/2, canvas.getWidth()/2, newBitmapSquareWidth/2, borderPaint);    
  • 与GlideApp对比

  如果Android项目中仅少的使用圆角图片且无需加载网络图片,此方法更为简单合适,不需要添加依赖以及很多的代码。GlideApp加载网络图片较为方便,以及一些内存缓存的机制。

原文地址:https://www.cnblogs.com/xqz0618/p/14913333.html