How to make an ImageView with rounded corners?

前端 未结 30 2485
天涯浪人
天涯浪人 2020-11-21 05:39

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

30条回答
  •  灰色年华
    2020-11-21 06:22

    Thanks a lot to first answer. Here is modified version to convert a rectangular image into a square one (and rounded) and fill color is being passed as parameter.

    public static Bitmap getRoundedBitmap(Bitmap bitmap, int pixels, int color) {
    
        Bitmap inpBitmap = bitmap;
        int width = 0;
        int height = 0;
        width = inpBitmap.getWidth();
        height = inpBitmap.getHeight();
    
        if (width <= height) {
            height = width;
        } else {
            width = height;
        }
    
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
    
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, width, height);
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
    
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(inpBitmap, rect, rect, paint);
    
        return output;
    }
    

提交回复
热议问题