Make ImageView fit width of CardView

前端 未结 10 676
太阳男子
太阳男子 2020-12-04 11:00

I have a CardView with rounded corners, I want to have an ImageView at the top like shown in the example taken from the material design guidelines

10条回答
  •  攒了一身酷
    2020-12-04 11:44

    I tried using the MaskedCardView and worked for me

        class MaskedCardView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = R.attr.materialCardViewStyle
    ) : MaterialCardView(context, attrs, defStyle) {
        @SuppressLint("RestrictedApi")
        private val pathProvider = ShapeAppearancePathProvider()
        private val path: Path = Path()
        private val shapeAppearance: ShapeAppearanceModel = ShapeAppearanceModel.builder(
            context,
            attrs,
            defStyle,
            R.style.Widget_MaterialComponents_CardView
        ).build()
    
        private val rectF = RectF(0f, 0f, 0f, 0f)
    
        override fun onDraw(canvas: Canvas) {
            canvas.clipPath(path)
            super.onDraw(canvas)
        }
    
        @SuppressLint("RestrictedApi")
        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            rectF.right = w.toFloat()
            rectF.bottom = h.toFloat()
            pathProvider.calculatePath(shapeAppearance, 1f, rectF, path)
            super.onSizeChanged(w, h, oldw, oldh)
        }
    }
    

    And use with it the attribute app:cardPreventCornerOverlap="false"

提交回复
热议问题