Android几种方式实现控件圆角

目前想到的能实现圆角的方式有这么几种:
1、使用shape元素(比较常用)
2、使用背景图片(有点蠢,还得让UI切图,不建议这种方式)
3、自定义控件实现
4、使用ViewOutlineProvider裁剪view
5、使用cardView
6、其他第三方库

下面来详细说明一下,如何用上面的方式实现圆角Button:

1、使用shape元素

在drawable文件夹中新建一个shape.xml文件,之后布局文件中设置背景颜色为shape.xml即可。利用shape元素实现圆角:



       
       
     


使用shape元素的优点是:方便简洁且直观,可以在项目中先定义好通用的控件样式,其他需要同样样式的按钮直接设置背景颜色就可以了,缺点是一个xml文件只能写定一种样式,如果项目中需要多种样式则每种不同的样式都需要一个专门的xml文件。

2、使用切图就不多说了,使用起来不方便。

3、自定义Button

第一步:在values文件中新建attrs文件,然后在resources中写入要自定义的属性



    

        
        
        
        

    


第二步,自定义class文件,继承自Button或者AppCompatButton

public class CustomButton extends AppCompatButton {

    // 圆角半径
    private float radius = getResources().getDimension(R.dimen.x6);
    // 按钮正常时的背景颜色
    private int normalColor;

    private GradientDrawable gradientDrawable;

    public CustomButton(Context context) {
        this(context, null, 0);
    }

    public CustomButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initAttris(attrs);
        init();
    }

    private void init() {

        setGravity(Gravity.CENTER);
        gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadius(radius);
        gradientDrawable.setColor(normalColor);
        // 这句话一定不要忘记,不然没效果
        setBackground(gradientDrawable);
    }

    /**
     * 属行初始化
     * @param attrs
     */
    private void initAttris(AttributeSet attrs) {
        if (attrs != null) {  // 获取自定义属性
            TypedArray typedArray  = getContext().obtainStyledAttributes(attrs, R.styleable.CustomButton);
            radius = (int) typedArray .getDimension(R.styleable.CustomButton_radius, getResources().getDimension(R.dimen.x6));
            int defaultColor = getResources().getColor(R.color.base_blue);
            normalColor = typedArray.getColor(R.styleable.CustomButton_normal_color, defaultColor);
            typedArray.recycle();
        }
    }
}

第三步,在xml文件中使用自定义按钮,其中app:radius,app:normal_color即是使用自定义的属性设置。


使用自定义Button弥补了使用shape元素的缺点,当项目中需要很多不同的样式时,只需要修改对应的属性值即可。

4、使用ViewOutlineProvider

ViewOutlineProvider是Android 5.x引入的新特性,用于实现View的阴影和轮廓,用ViewOutlineProvider实现圆角实现圆角:

roundImage.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                // 设置按钮圆角率为30
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 30);
                // 设置按钮为圆形
                outline.setOval(0, 0, view.getWidth(), view.getHeight());
            }
        });
roundImage.setClipToOutline(true);
5、使用CardView

CardView是Android 5.0引入的卡片显示控件,可以实现阴影和圆角,通过设置cardCornerRadius来设置圆角半径



    


6、其他一些第三方的库有的也有圆角的功能,例如fresco,如果你项目中引入了fresco,那么可以通过设置下面的属行来设置圆角半径:

fresco:roundedCornerRadius="25dp"

相关文章:你不知道的圆形圆角处理方式

你可能感兴趣的:(Android几种方式实现控件圆角)