我如何制作圆角布局?我想应用圆角到我的线性布局。


当前回答

如果你想要的只是一个简单的圆角矩形,长话短说。

float r=8;
ShapeDrawable shape = 
   new ShapeDrawable (new RoundRectShape(new float[] { r, r, r, r, r, r, r, r },null,null));
shape.getPaint().setColor(Color.RED);
view.setBackground(shape);

前两个浮动用于左上角(其余对按顺时针方向对应)。

要了解更多细节,请阅读这个答案

其他回答

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="3dip" android:color="#B1BCBE" />
    <corners android:radius="10dip"/>
    <padding android:left="3dip" android:top="3dip" android:right="3dip" android:bottom="3dip" />
</shape>

@David,只是把padding的值和stroke一样,所以无论图像大小,边框都是可见的

下面是一个XML文件的副本,用于创建一个具有白色背景,黑色边框和圆角的可绘制对象:

 <?xml version="1.0" encoding="UTF-8"?> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
        <solid android:color="#ffffffff"/>    

        <stroke android:width="3dp"
                android:color="#ff000000"
                />

        <padding android:left="1dp"
                 android:top="1dp"
                 android:right="1dp"
                 android:bottom="1dp"
                 /> 

        <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
    </shape>

将其保存为可绘制目录下的XML文件, 使用它就像使用任何可绘制的背景(图标或资源文件),使用它的资源名(R.drawable.your_xml_name)

你可以用自定义视图来做,像这个RoundAppBar和RoundBottomAppBar。 这里有一个路径用于clipPath画布。

函数以编程方式设置角半径

static void setCornerRadius(GradientDrawable drawable, float topLeft,
        float topRight, float bottomRight, float bottomLeft) {
    drawable.setCornerRadii(new float[] { topLeft, topLeft, topRight, topRight,
            bottomRight, bottomRight, bottomLeft, bottomLeft });
}

static void setCornerRadius(GradientDrawable drawable, float radius) {
    drawable.setCornerRadius(radius);
}

使用

GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(Color.GREEN);
setCornerRadius(gradientDrawable, 20f);
//or setCornerRadius(gradientDrawable, 20f, 40f, 60f, 80f); 

view.setBackground(gradientDrawable);

对于API 21+,使用剪辑视图

在API 21中,圆形轮廓剪辑被添加到View类中。更多信息请参见培训文档或参考资料。

这个内置的功能使圆角非常容易实现。它适用于任何视图或布局,并支持适当的剪辑。

下面是该怎么做:

创建一个可绘制的圆形形状,并将其设置为视图的背景: android:背景= " @drawable / round_outline” 在代码中剪辑轮廓:setClipToOutline(true)

文档曾经说过,你可以设置android:clipToOutline=“true”的XML,但这个错误现在终于解决了,文档现在正确地指出,你只能在代码中这样做。

它的样子:

关于ImageViews的特别说明

setClipToOutline()仅在视图的背景设置为可绘制的形状时才有效。如果此背景形状存在,视图将背景的轮廓作为剪切和阴影目的的边界。

这意味着如果你想圆角的ImageView与setClipToOutline(),你的图像必须来自android:src而不是android:background(因为背景是用于圆角形状)。如果你必须使用背景来设置你的图像而不是src,你可以使用这个嵌套视图的解决方案:

创建一个外部布局,将其背景设置为可绘制的形状 将布局包装在ImageView周围(没有填充) ImageView(包括布局中的任何其他内容)现在将被剪切到外部布局的圆形形状。