How to make an ImageView with rounded corners?

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

    None of the methods provided in the answers worked for me. I found the following way works if your android version is 5.0 or above:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    
                        ViewOutlineProvider provider = new ViewOutlineProvider() {
                            @Override
                            public void getOutline(View view, Outline outline) {
                                int curveRadius = 24;
                                outline.setRoundRect(0, 0, view.getWidth(), (view.getHeight()+curveRadius), curveRadius);
                            }
                        };
                        imageview.setOutlineProvider(provider);
                        imageview.setClipToOutline(true);
            }   
    

    No xml shapes to be defined, and the code above create corners only for top, which normal methods won't work. If you need 4 corners to be rounded, remove:

    "+ curveRadius"  
    

    From the parameter for bottom in setRoundRect. You can further expand the shape to any others by specifying outlines that suit your needs. Check out the following link:

    Android Developer Documentation.

提交回复
热议问题