自定义 Drawable 不为 CardView 的图像生成圆角

Custom Drawable not generating round corners for CardView's image

我用新的 CardView 和 RecyclerView 创建了一个卡片列表,看起来是这样的:

我已经尝试按照 Mariotti 在 this post.

中的解释修改带有圆角的卡片

PROBLEM: The problem is that, as you can see from the screenshot I am only able to set the card's corner while the image remains squared.

在示例中,自定义 Drawable class 扩展 Drawable 使用 Canvas.drawRoundRect() 绘制圆角矩形,并使用 PaintBitmapShader 用纹理而不是简单的颜色填充圆角矩形,如 here.

所述

在我的适配器中我有:

@Override
public ContactViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
    final View itemView = LayoutInflater
                    .from(viewGroup.getContext())
                    .inflate(R.layout.item_card_view, viewGroup, false);
    CardView cardView = (CardView) itemView.findViewById(R.id.card_view);

    ImageView imageView = (ImageView) itemView.findViewById(R.id.hImage);

    Bitmap mBitmap = BitmapFactory.decodeResource(itemView.getResources(), R.drawable.background);
    //Default
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        //Default
        imageView.setBackgroundResource(R.drawable.background);
    } else {
        //RoundCorners
        madapps.hellogridview.RoundCornersDrawable round = new madapps.hellogridview.RoundCornersDrawable(
                mBitmap,            
             itemView.getResources().getDimension(R.dimen.cardview_default_radius)
                , 5); //or your custom radius

        cardView.setPreventCornerOverlap(false); //it is very important

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            imageView.setBackground(round);
        else
            imageView.setBackgroundDrawable(round);
    }

    //Set onClick listener
    cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int tag = (Integer) v.findViewById(R.id.hTitle).getTag();
            Toast.makeText(viewGroup.getContext(), "Clickable card no: "+tag, Toast.LENGTH_LONG).show();
        }
    });
    return new ContactViewHolder(itemView);
}

并且我已经将 R.dimen.cardview_default_radius 的值覆盖为 8dp,但没有结果!有什么想法吗?

我已经用这个解决了:

https://github.com/pungrue26/SelectableRoundedImageView

并将半径 10dp(与卡片相同)应用于图像的顶角:

<com.joooonho.SelectableRoundedImageView  android:id="@+id/headerImage"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"     
    android:layout_width="wrap_content"
    android:src="@drawable/cardbackground3"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    app:sriv_left_top_corner_radius="10dip"
    app:sriv_right_top_corner_radius="10dip"
    app:sriv_left_bottom_corner_radius="0dip"
    app:sriv_right_bottom_corner_radius="0dip"
    app:sriv_border_color="#333333"/>

谢谢,这正是我所需要的。但是你知道有一个问题知道。在 CardView 和 Image 的边界之间几乎没有 space 填充。但是我的情况下没有填充物。在我看来,这个图书馆圆角但不改变图像的位置。你有同样的想法吗?顺便说一句,我的布局和你的一样。你对此有什么想法吗?