How to make an ImageView with rounded corners?

前端 未结 30 3160
天涯浪人
天涯浪人 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:28

    While the above answer works, Romain Guy (a core Android developer) shows a better method in his blog which uses less memory by using a shader not creating a copy of the bitmap. The general gist of the functionality is here:

    BitmapShader shader;
    shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);
    
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    
    // rect contains the bounds of the shape
    // radius is the radius in pixels of the rounded corners
    // paint contains the shader that will texture the shape
    canvas.drawRoundRect(rect, radius, radius, paint);
    

    The advantages of this over other methods is that it:

    • does not create a separate copy of the bitmap, which uses a lot of memory with large images [vs most of the other answers here]
    • supports antialisasing [vs clipPath method]
    • supports alpha [vs xfermode+porterduff method]
    • supports hardware acceleration [vs clipPath method]
    • only draws once to the canvas [vs xfermode and clippath methods]

    I've created a RoundedImageView based off this code that wraps this logic into an ImageView and adds proper ScaleType support and an optional rounded border.

提交回复
热议问题