CardView Radius 和 Drawable Shape Radius 不一样

CardView Radius and Drawable Shape Radius are not same

我有以下布局 CardView

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:padding="50dp"
    >
  <androidx.cardview.widget.CardView
      android:layout_width="match_parent"
      android:layout_height="200dp"
      app:cardBackgroundColor="@android:color/holo_red_light"
      app:cardCornerRadius="50dp"
      app:cardElevation="0dp"
      app:layout_constraintTop_toTopOf="parent"
      >
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/outline"
        />
  </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

而我的@drawable/outline只是一个角半径与cardCornerRadius

相同的笔画
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="50dp" />
  <stroke
      android:width="3dp"
      android:color="@color/white" />
</shape>

所以,我期待 CardView 有轮廓。但这就是我得到的

为什么我的stoke半径和CardView的半径不一样,如何解决?

Check this issue on MaterialCardView(但与androidx.cardview.widget.CardView相同)

It is due to Anti aliasing. The background and the stroke are drawn on the same pixels but depending on the color of the stroke the transparent pixels added by the AA can cause the bleed through. That's why you won't see it if you invert the colors here.

您只需使用

即可获得相同的视图
   <com.google.android.material.card.MaterialCardView
        app:cardBackgroundColor="@color/...."
        app:strokeWidth="3dp"
        app:strokeColor="@color/white />

如您所见:

你还有另一个选择。
您可以将相同的ShapeAppearanceModel默认MaterialCardView提供)应用于简单的View(或Layout反转颜色将边距应用到内部视图。

   <com.google.android.material.card.MaterialCardView
        app:cardCornerRadius="@dimen/corner_radius_16"
        app:cardBackgroundColor="@color/white">

        <View
            android:layout_margin="3dp"   
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/view_rounded"/>

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

然后:

float size = getResources().getDimension(R.dimen.cutout_size);

View viewRounded = findViewById(R.id.view_rounded);
ShapeAppearanceModel shapeAppearanceModelView = new ShapeAppearanceModel()
        .toBuilder()
        .setAllCorners(CornerFamily.ROUNDED,radius16)
        .build();
MaterialShapeDrawable shapeDrawableView = new MaterialShapeDrawable(shapeAppearanceModelView);
shapeDrawableView.setFillColor(ContextCompat.getColorStateList(this,R.color.xxx));
ViewCompat.setBackground(viewRounded,shapeDrawableView);