首页 > 解决方案 > GradientDrawable.setCornerRadii 的剪辑不起作用

问题描述

我正在尝试创建一个具有自定义半径的视图,但在使用 GradientDrawable.setCornerRadii 时遇到问题...
如果我使用下面的代码,则视图会剪辑其中的所有子视图

public void SetCornerRadius(View v,int Radius){
        GradientDrawable shape = new GradientDrawable();
        shape.setShape(GradientDrawable.RECTANGLE);
        shape.setCornerRadius((int)Px2Dp(Radius));
        v.setBackground(shape);
        v.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
        v.setClipToOutline(true);
    }

但是,如果我对不同的拐角半径使用下面的代码,那么由于子视图超出了父视图,因此剪辑无法按预期工作

public void SetDifferentCornerRadius(View v,int TopLeftRadius,int TopRightRadius,int BottomLeftRadius,int BottomRightRadius,String backgroundColor){
        GradientDrawable shape = new GradientDrawable();
        ViewGroup vg = (ViewGroup)v;
        shape.setShape(GradientDrawable.RECTANGLE);
        shape.setColor(Color.parseColor(backgroundColor));
        shape.setCornerRadii(new float[] { (int)Px2Dp(TopLeftRadius),(int)Px2Dp(TopLeftRadius),(int)Px2Dp(TopRightRadius),(int)Px2Dp(TopRightRadius),(int)Px2Dp(BottomRightRadius),(int)Px2Dp(BottomRightRadius),(int)Px2Dp(BottomLeftRadius),(int)Px2Dp(BottomLeftRadius)});
        v.setBackground(shape);
        v.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
        v.setClipToOutline(true);

    }

标签: androidviewandroid-viewcornerradiusandroid-gradient-drawable

解决方案


我猜它不起作用,因为setClipToOutline只适用于下面的形状。

目前,只有可以表示为矩形、圆形或圆形矩形的轮廓支持剪切。

https://developer.android.com/reference/android/graphics/Outline#canClip()


推荐阅读