美文网首页
Android长方形图片生成正圆形,以及矩形图片生成圆角

Android长方形图片生成正圆形,以及矩形图片生成圆角

作者: 火星局 | 来源:发表于2020-04-07 18:21 被阅读0次

    一般要做正圆形图片,只能是正方形的基础上才能实现,否则就变成椭圆了,下面说说如何使长方形的图片生成正圆形图片

    废话不多说,没图没真相,先上图吧:

    原图.png

    变成正圆后:


    变成正圆后.png

    下面上代码:

     public static Bitmap makeRoundCorner(Bitmap bitmap)
        {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int left = 0, top = 0, right = width, bottom = height;
            float roundPx = height/2;
            if (width > height) {
                left = (width - height)/2;
                top = 0;
                right = left + height;
                bottom = height;
            } else if (height > width) {
                left = 0;
                top = (height - width)/2;
                right = width;
                bottom = top + width;
                roundPx = width/2;
            }
            ZLog.i(TAG, "ps:"+ left +", "+ top +", "+ right +", "+ bottom);
    
            Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            int color = 0xff424242;
            Paint paint = new Paint();
            Rect rect = new Rect(left, top, right, bottom);
            RectF rectF = new RectF(rect);
    
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        }
    
    

    下面再解释下:

    由于图片是长方形,所以图片的 宽、高 肯定会有一边要小于另一边,要生成正方形就已最小的一边为基准,再来裁切定位另一边的显示范围

    至于圆角的半径则是正方形宽的一半,用过 CSS 的就知道,画圆很方便 border-radius设为 50% 就可以了,都是一个道理

    android 的 UI 真是太繁琐了

      public static Bitmap makeRoundCorner(Bitmap bitmap, int px)
        {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            int color = 0xff424242;
            Paint paint = new Paint();
            Rect rect = new Rect(0, 0, width, height);
            RectF rectF = new RectF(rect);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, px, px, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        }
    
    

    参考

    相关文章

      网友评论

          本文标题:Android长方形图片生成正圆形,以及矩形图片生成圆角

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