美文网首页
仿支付宝头像外加一个边框的工具类

仿支付宝头像外加一个边框的工具类

作者: 大尹EIE | 来源:发表于2017-09-11 10:40 被阅读0次

    代码:

    /**
         * 获取圆角矩形或圆形图片的方法
         *
         * @param bitmap 待处理 bitmap 对象
         * @param pixels 圆角半径,x 和 y 相等
         * @return 返回圆角或者圆形 bitmap
         */
        public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
    
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;
    
            paint.setAntiAlias(true);
            //柱:一定要先画圆角矩形
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        }
    
        /**
         * 获取待边框的圆角矩形或圆形图片方法
         *
         * @param resources          {@link Resources}
         * @param resId              对应资源 id
         * @param borderCornerRadius 边框圆角半径,x 和 y 相等
         * @return 圆角矩形或圆形 bitmap 对象
         */
        public static Bitmap getRoundCornerBitmapWithBorder(Resources resources, int resId, int borderCornerRadius) {
            Bitmap src = BitmapFactory.decodeResource(resources, resId);
            Bitmap temp_out = getRoundedCornerBitmap(src, 0);//图片默认为矩形的
            Bitmap out = Bitmap.createBitmap(temp_out.getWidth(), temp_out.getHeight(), Bitmap.Config.ARGB_8888);
            //新建画布
            Canvas canvas = new Canvas(out);
            //原始大小的矩形
            Rect rect = new Rect(0, 0, temp_out.getWidth(), temp_out.getHeight());
            //矩形宽高的两边都缩小 10
            Rect insetRect = new Rect(rect);
            //外面白色变宽宽度 默认为 10
            final int borderWidth = 8;
            //缩小矩形
            insetRect.inset(borderWidth, borderWidth);
    
            Paint paint = new Paint();
            //把图像信息画在缩小后的矩形区域内
            canvas.drawBitmap(temp_out, rect, insetRect, paint);
    
            paint.setAntiAlias(true);
            paint.setColor(0xFFCE3D3A);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(borderWidth);
            //画边框线
            canvas.drawRoundRect(new RectF(insetRect), borderCornerRadius, borderCornerRadius, paint);
            return out;
        }
    

    注:getRoundedCornerBitmap() 方法中一定要先画圆角矩形,原因可以看一下上篇文章:

    安卓 Paint 的 Xfermode

    调用:

    iv.setImageBitmap(BitmapHelper.getRoundCornerBitmapWithBorder(getResources(), R.mipmap.icon_avater, 14));
    

    效果:

    效果图

    相关文章

      网友评论

          本文标题:仿支付宝头像外加一个边框的工具类

          本文链接:https://www.haomeiwen.com/subject/vrixsxtx.html