ChatGPT解决这个技术问题 Extra ChatGPT

如何制作带圆角的布局..?

如何制作带有圆角的布局?我想为我的 LinearLayout 应用圆角。

您只需要将圆形图像设置为布局的背景,否则按照第一条评论中的说明制作形状
你只需要搜索 SO... 你会发现很多答案 ..
角落对我来说是模糊的
谷歌有新框架,新技术更好Jetpack Compose

P
Pankaj Dhawan

1:在drawables中定义layout_bg.xml:

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

2:将 layout_bg.xml 添加为布局的背景

android:background="@drawable/layout_bg"

这行不通。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有在角上绘制的内容,您将不会看到它们被圆角。
几乎总是,我的内容从不涵盖角落。这完美地工作。
如何避免错误Element shape doesn't have the required attribute android:layout_height
Element shape doesn't have the required attribute android:layout_height 显示错误的原因是 layout_bg.xml 不在可绘制文件夹中。
@nhouser9:实际上它更像是“它有效,但请注意您的前景/内容可能会出现在角落里”。因此,根据用例,它可能 100% 有效。我很高兴答案没有那么多反对票,因为它很有用,我很高兴评论有一百个赞成票,因为很容易发现这个解决方案的局限性。两全其美。
C
Cristan

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

API 21 中的 View 类添加了圆形轮廓剪裁。有关详细信息,请参阅此 training doc 或此 reference

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

这是做什么:

创建一个圆形可绘制对象并将其设置为视图的背景:android:background="@drawable/round_outline"

剪辑到代码中的轮廓:setClipToOutline(true)

文档曾经说您可以设置 android:clipToOutline="true" XML,但现在终于解决了 this bug,并且文档现在正确地指出您只能在代码中执行此操作。

它看起来像什么:

https://i.stack.imgur.com/6NlvO.png

关于 ImageViews 的特别说明

setClipToOutline() 仅在视图的背景设置为可绘制形状时有效。如果存在此背景形状,View 会将背景的轮廓视为边界,以进行剪切和阴影处理。

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

创建一个外部布局,其背景设置为您的可绘制形状

将该布局包裹在您的 ImageView 周围(没有填充)

ImageView(包括布局中的任何其他内容)现在将被裁剪为外部布局的圆形。


不适用于低于 21 的 API。不能等到我只能支持 API 21。
使用 'setClipToOutline' 有效,但它也会删除框架本身(用于背景的可绘制对象)。有没有办法避免这种情况?
您是否阅读了我关于使用 src=@drawable... 而不是 background=@drawable 的说明?您可以这样做,也可以将 ImageView 嵌套在包含形状轮廓的容器视图中。
每个人都在评论那个错误——它已经有将近三年的历史了,而且在这十年中的任何时候都没有得到修复的迹象。让我们施加一些压力。
@FebinMathew 你不能。
k
kyogs

这是一个 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)


喜欢圆特定角落的可能性
这个答案几乎就是上面的答案。这里唯一真正的变化是每个拐角半径的定义,并且给定每个拐角的相同值,我会将其写在一行中:<corners android:radius="7dp" /> :)
这对我来说是最好的答案,因为它涵盖了圆角特定角落的可用性......干得好,100%有效
ImageView 的角不是圆角(剪裁),我该如何解决?
E
Evan JIANG

在 android v7 支持库中使用 CardView。虽然它有点重,但它解决了所有问题,而且很容易。不像 set drawable background 方法,它可以成功地裁剪子视图。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="@android:color/transparent"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="0dp"
    card_view:contentPadding="0dp">
    <YOUR_LINEARLAYOUT_HERE>
</android.support.v7.widget.CardView>

对于能够“负担得起”它的每个人来说,这比其他任何事情都要好得多。让我感到困惑的是,这样一个基本的东西并不是标准 Android 视图的一部分,它是几乎所有 Web 浏览器的 CSS 的主要内容
C
Community

我已经这样做了:

检查截图:

https://i.stack.imgur.com/DxWqN.png

drawable 文件夹中创建以 custom_rectangle.xml 命名的 drawable 文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@android:color/white" />

    <corners android:radius="10dip" />

    <stroke
        android:width="1dp"
        android:color="@android:color/white" />

</shape>

现在在视图上应用矩形背景:

mView.setBackground(R.drawlable.custom_rectangle);

完毕


这行不通。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有在角上绘制的内容,您将不会看到它们被圆角。
a
android developer

我认为更好的方法是合并两件事:

制作布局的位图,如此处所示。从位图制作一个圆形可绘制对象,如此处所示将可绘制对象设置在 imageView 上。

这将处理其他解决方案未能解决的情况,例如具有角落的内容。

我认为它对 GPU 也更友好一些,因为它显示的是单层而不是 2 。

唯一更好的方法是制作一个完全自定义的视图,但这需要很多代码并且可能需要很多时间。我认为我在这里提出的建议是两全其美的。

这是如何完成的一个片段:

RoundedCornersDrawable.java

/**
 * shows a bitmap as if it had rounded corners. based on :
 * http://rahulswackyworld.blogspot.co.il/2013/04/android-drawables-with-rounded_7.html
 * easy alternative from support library: RoundedBitmapDrawableFactory.create( ...) ; 
 */
public class RoundedCornersDrawable extends BitmapDrawable {

    private final BitmapShader bitmapShader;
    private final Paint p;
    private final RectF rect;
    private final float borderRadius;

    public RoundedCornersDrawable(final Resources resources, final Bitmap bitmap, final float borderRadius) {
        super(resources, bitmap);
        bitmapShader = new BitmapShader(getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        final Bitmap b = getBitmap();
        p = getPaint();
        p.setAntiAlias(true);
        p.setShader(bitmapShader);
        final int w = b.getWidth(), h = b.getHeight();
        rect = new RectF(0, 0, w, h);
        this.borderRadius = borderRadius < 0 ? 0.15f * Math.min(w, h) : borderRadius;
    }

    @Override
    public void draw(final Canvas canvas) {
        canvas.drawRoundRect(rect, borderRadius, borderRadius, p);
    }
}

自定义视图.java

public class CustomView extends ImageView {
    private View mMainContainer;
    private boolean mIsDirty=false;

    // TODO for each change of views/content, set mIsDirty to true and call invalidate

    @Override
    protected void onDraw(final Canvas canvas) {
        if (mIsDirty) {
            mIsDirty = false;
            drawContent();
            return;
        }
        super.onDraw(canvas);
    }

    /**
     * draws the view's content to a bitmap. code based on :
     * http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
     */
    public static Bitmap drawToBitmap(final View viewToDrawFrom, final int width, final int height) {
        // Create a new bitmap and a new canvas using that bitmap
        final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bmp);
        viewToDrawFrom.setDrawingCacheEnabled(true);
        // Supply measurements
        viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
        // Apply the measures so the layout would resize before drawing.
        viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
        // and now the bmp object will actually contain the requested layout
        canvas.drawBitmap(viewToDrawFrom.getDrawingCache(), 0, 0, new Paint());
        return bmp;
    }

    private void drawContent() {
        if (getMeasuredWidth() <= 0 || getMeasuredHeight() <= 0)
            return;
        final Bitmap bitmap = drawToBitmap(mMainContainer, getMeasuredWidth(), getMeasuredHeight());
        final RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bitmap, 15);
        setImageDrawable(drawable);
    }

}

编辑:找到了一个不错的替代方案,基于 "RoundKornersLayouts" library。有一个类将用于您希望扩展的所有布局类,并进行四舍五入:

//based on https://github.com/JcMinarro/RoundKornerLayouts
class CanvasRounder(cornerRadius: Float, cornerStrokeColor: Int = 0, cornerStrokeWidth: Float = 0F) {
    private val path = android.graphics.Path()
    private lateinit var rectF: RectF
    private var strokePaint: Paint?
    var cornerRadius: Float = cornerRadius
        set(value) {
            field = value
            resetPath()
        }

    init {
        if (cornerStrokeWidth <= 0)
            strokePaint = null
        else {
            strokePaint = Paint()
            strokePaint!!.style = Paint.Style.STROKE
            strokePaint!!.isAntiAlias = true
            strokePaint!!.color = cornerStrokeColor
            strokePaint!!.strokeWidth = cornerStrokeWidth
        }
    }

    fun round(canvas: Canvas, drawFunction: (Canvas) -> Unit) {
        val save = canvas.save()
        canvas.clipPath(path)
        drawFunction(canvas)
        if (strokePaint != null)
            canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, strokePaint)
        canvas.restoreToCount(save)
    }

    fun updateSize(currentWidth: Int, currentHeight: Int) {
        rectF = android.graphics.RectF(0f, 0f, currentWidth.toFloat(), currentHeight.toFloat())
        resetPath()
    }

    private fun resetPath() {
        path.reset()
        path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW)
        path.close()
    }

}

然后,在您自定义的每个布局类中,添加与此类似的代码:

class RoundedConstraintLayout : ConstraintLayout {
    private lateinit var canvasRounder: CanvasRounder

    constructor(context: Context) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs, defStyle)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornersView, 0, 0)
        val cornerRadius = array.getDimension(R.styleable.RoundedCornersView_corner_radius, 0f)
        val cornerStrokeColor = array.getColor(R.styleable.RoundedCornersView_corner_stroke_color, 0)
        val cornerStrokeWidth = array.getDimension(R.styleable.RoundedCornersView_corner_stroke_width, 0f)
        array.recycle()
        canvasRounder = CanvasRounder(cornerRadius,cornerStrokeColor,cornerStrokeWidth)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(FrameLayout.LAYER_TYPE_SOFTWARE, null)
        }
    }

    override fun onSizeChanged(currentWidth: Int, currentHeight: Int, oldWidth: Int, oldheight: Int) {
        super.onSizeChanged(currentWidth, currentHeight, oldWidth, oldheight)
        canvasRounder.updateSize(currentWidth, currentHeight)
    }

    override fun draw(canvas: Canvas) = canvasRounder.round(canvas) { super.draw(canvas) }

    override fun dispatchDraw(canvas: Canvas) = canvasRounder.round(canvas) { super.dispatchDraw(canvas) }

}

如果您希望支持属性,请按照库中的说明使用:

<resources>
  <declare-styleable name="RoundedCornersView">
      <attr name="corner_radius" format="dimension"/>
      <attr name="corner_stroke_width" format="dimension"/>
      <attr name="corner_stroke_color" format="color"/>
  </declare-styleable>
</resources>

另一种选择,对于大多数用途来说可能更容易:使用 MaterialCardView 。它允许自定义圆角、笔触颜色和宽度以及高度。

例子:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"
    tools:context=".MainActivity">

    <com.google.android.material.card.MaterialCardView
        android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center"
        app:cardCornerRadius="8dp" app:cardElevation="8dp" app:strokeColor="#f00" app:strokeWidth="2dp">

        <ImageView
            android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0f0"/>

    </com.google.android.material.card.MaterialCardView>

</FrameLayout>

结果:

https://i.stack.imgur.com/UXPtb.png

请注意,如果您使用它,笔画的边缘会出现轻微的伪影问题(在那里会留下一些内容像素)。如果放大,您会注意到它。我已经报告了这个问题here

编辑:似乎是固定的,但不是在 IDE 上。已报告 here


感谢您收集这个很棒的答案,它让我朝着正确的方向前进,但我可以在这里使用一些非常相关的问题的帮助stackoverflow.com/questions/25877515/…
这会产生错误,因为 ImageView 中没有可用的默认构造函数。
这应该被接受的答案。而不是平面逻辑,你去寻找一个很棒的解决方案。这也解决了您在对其他答案的评论中提到的问题。感谢您的努力,也许您可以纠正一个功能齐全的类并通过 github 分享。我认为它可能会帮助太多人。
@Senhor 你认为我应该吗?我会考虑的。现在,您可以在此处查看我创建的其他存储库:github.com/AndroidDeveloperLB?tab=repositories
作为它的很大一部分,你可以试一试。顺便说一句,autofittextview 看起来真的很酷。
P
Pang

如果你想让你的布局变得圆润,最好使用 CardView,它提供了许多使设计美观的功能。

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="5dp">
      <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".3"
                android:text="@string/quote_code"
                android:textColor="@color/white"
                android:textSize="@dimen/text_head_size" />
      </LinearLayout>
</android.support.v7.widget.CardView>

使用此 card_view:cardCornerRadius="5dp",您可以更改半径。


S
Silambarasan Poonguti

尝试这个...

1.创建可绘制的xml(custom_layout.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<solid android:color="#FFFFFF" />

<stroke
    android:width="2dp"
    android:color="#FF785C" />

<corners android:radius="10dp" />

</shape>

2.添加您的视图背景

android:background="@drawable/custom_layout"

就像我在上面写的类似解决方案一样:这不起作用。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有在角上绘制的内容,您将不会看到它们被圆角。
A
Abdul Basit Rishi

步骤 1:在 drawables 文件夹中定义 bg_layout.xml,并将以下代码放入其中。

第 2 步:将 bg_layout.xml 作为背景添加到您的布局中,完成。

    <?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="#EEEEEE"/> <!--your desired colour for solid-->

    <stroke
        android:width="3dp"
        android:color="#EEEEEE" /> <!--your desired colour for border-->

    <corners
        android:radius="50dp"/> <!--shape rounded value-->

</shape>

G
Gabriele Mariotti

借助材料组件库,您可以使用 MaterialShapeDrawabledraw custom shapes

只需将 LinearLayout 放入您的 xml 布局中:

<LinearLayout
    android:id="@+id/linear_rounded"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ..>

    <!-- content ..... -->

</LinearLayout>

然后,您可以在您的代码中应用 ShapeAppearanceModel。就像是:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

LinearLayout linearLayout= findViewById(R.id.linear_rounded);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,radius)
    .build();

MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
//Fill the LinearLayout with your color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.secondaryLightColor));


ViewCompat.setBackground(linearLayout,shapeDrawable);

https://i.stack.imgur.com/t5A7T.png

注意::它需要材料组件库的 1.1.0 版本。


这是我的观察,希望能对某人有所帮助。如果你为上面设置了错误的半径(过高,比如 56 而不是 20,例如如果控制高度为 40),上面的角无论如何都会显示正确,但仅从 api 21 开始。对于 api 19,它们会非常混乱up :) 除非您输入正确的半径。
D
Divyanshu Maithani

最好和最简单的方法是在布局中使用可绘制的 card_background。这也遵循 Google 的材料设计指南。只需将其包含在您的 LinearLayout 中:

android:background="@drawable/card_background"

将此添加到您的可绘制目录并将其命名为 card_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="#BDBDBD"/>
            <corners android:radius="5dp"/>
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="0dp"
        android:top="0dp"
        android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <corners android:radius="5dp"/>
        </shape>
    </item>
</layer-list>

L
Linh

以编程方式设置拐角半径的功能

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);

v
vishnuc156

使用 CardView 为任何布局获取圆角边缘。使用 card_view:cardCornerRadius="5dp" 为 cardview 获得圆润的布局边缘。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

      <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="5dp">
          <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp"
                android:weightSum="1">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".3"
                    android:text="@string/quote_code"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".7"
                    android:text="@string/quote_details"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />
            </LinearLayout>
       </android.support.v7.widget.CardView>
   </LinearLayout>

来自 support.v7 库的 CardView,您可以从 API7 或更高版本中使用。
A
Abdul Wasae

更好的方法是:

背景活动.xml

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="fill">
        <color android:color="@color/black"/>
    </item>
    <item>
        <shape android:gravity="fill">
            <solid android:color="@color/white"/>
            <corners android:radius="10dip"/>
            <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
        </shape>
    </item>
</layer-list>

这也将在 API 21 下工作,并为您提供如下内容:

https://i.stack.imgur.com/FMSFD.png

如果您愿意为更好的控制付出更多努力,那么使用 android.support.v7.widget.CardView 及其 cardCornerRadius 属性(并将 elevation 属性设置为 0dp 以消除与 cardView 一起出现的任何阴影)。此外,这将在 API 级别低至 15 时起作用。


如果内容适合背景,它将覆盖它。它并没有真正剪辑到您设置的形状。
你是说另一种观点?您能否更新代码以显示您的意思?这个想法是圆角不会放置黑色区域。在角落周围,应该有透明的颜色。
哦,我现在明白你的问题了。我想为此,您可以在内容上使用一个小的固定边距
但是,内容不会被切割成您选择的形状,因为固定边距是矩形的,而不是根据您选择的形状。
W
Wesely

在 drawable 中创建您的 xml,layout_background.xml

 <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
      <solid android:color="@color/your_colour" />
      <stroke
            android:width="2dp"
            android:color="@color/your_colour" />
      <corners android:radius="10dp" />      
    </shape>
 <--width, color, radius should be as per your requirement-->

然后,将其添加到您的 layout.xml

 android:background="@drawable/layout_background"

p
paezinc
<?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,只需将填充值与中风相同,因此无论图像大小如何,边框都是可见的


Z
ZooMagic

我在@gauravsapiens 的回答中附上了我的评论,让您合理地理解这些参数会产生什么影响。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Background color -->
    <solid android:color="@color/white" />

    <!-- Stroke around the background, width and color -->
    <stroke android:width="4dp" android:color="@color/drop_shadow"/>

    <!-- The corners of the shape -->
    <corners android:radius="4dp"/>

    <!-- Padding for the background, e.g the Text inside a TextView will be 
    located differently -->
    <padding android:left="10dp" android:right="10dp" 
             android:bottom="10dp" android:top="10dp" />

</shape>

如果您只是想创建一个圆角的形状,删除填充和描边就可以了。如果您同时移除实体,您实际上将在透明背景上创建圆角。

为了懒惰,我在下面创建了一个形状,它只是一个带有圆角的纯白色背景 - 享受吧! :)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Background color -->
    <solid android:color="@color/white" />

    <!-- The corners of the shape -->
    <corners android:radius="4dp"/>

</shape>

K
Keval Patel
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="@dimen/_10sdp"
android:shape="rectangle">

<solid android:color="@color/header" />

<corners
    android:bottomLeftRadius="@dimen/_5sdp"
    android:bottomRightRadius="@dimen/_5sdp"
    android:topLeftRadius="@dimen/_5sdp"
    android:topRightRadius="@dimen/_5sdp" />


u
ucMedia

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

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);

https://i.stack.imgur.com/APiRB.jpg

前两个浮点数用于左上角(其余对顺时针对应)。

有关详细信息,请阅读 this answer


A
Ali Rezaiyan

您可以使用自定义视图来做到这一点,例如 RoundAppBarRoundBottomAppBar。这里使用 pathclipPath 画布。

https://i.stack.imgur.com/HaVVNl.jpg


Y
Yokich

我参加聚会有点晚了,但这仍然是个问题。所以我写了一组 OutlineProviders 和 BindingAdapters 用于数据绑定,使您能够从 xml 中剪裁角点。

注意:带轮廓的剪裁不支持不同大小的角!

我在 this stackoverflow post 上用代码写了详细的回复

使用代码 + 绑定适配器将获得什么:

<androidx.constraintlayout.widget.ConstraintLayout
    clipRadius="@{@dimen/some_radius}"
    clipBottomLeft="@{@dimen/some_radius}"
    clipBottomRight="@{@dimen/some_radius}"
    clipTopLeft="@{@dimen/some_radius}"
    clipTopRight="@{@dimen/some_radius}"
    clipCircle="@{@bool/clip}"

这使您可以将视图裁剪为圆形、圆角、一个方向的圆角(左、上、右、下)或单个角。


如果你只是想要一个圆形的背景,这太过分了,你最好使用可绘制的 xml。但是,如果您想在不突出图像的情况下修整布局的角落,这就是方法。