如何实现布局右下角斜角裁切?ShapeAppearanceModel未达预期
布局右下角斜角裁剪解决方案
问题分析
你当前的代码仅创建了ShapeAppearanceModel和MaterialShapeDrawable,但未给Drawable设置填充色,导致看起来没有效果;另外如果需要的是大斜角(而非小切角),CornerFamily.CUT的固定尺寸设置可能无法满足需求。
方案一:修正MaterialShapeDrawable实现(小切角场景)
如果需要的是小尺寸的斜切角,只需给Drawable补充填充色,并确保尺寸适配:
val shapeAppearanceModel = ShapeAppearanceModel() .toBuilder() // 将dp转成像素,适配不同分辨率(这里36dp为示例,可自行调整) .setBottomRightCorner(CornerFamily.CUT, resources.getDimension(R.dimen.corner_cut_size)) .build() val shapeDrawable = MaterialShapeDrawable(shapeAppearanceModel).apply { // 设置布局背景色(白色) fillColor = ContextCompat.getColorStateList(context, R.color.white) // 可选:设置边框,不需要可注释 // strokeWidth = resources.getDimensionPixelSize(R.dimen.stroke_width) // strokeColor = ContextCompat.getColorStateList(context, R.color.black) } ViewCompat.setBackground(shapedLayout, shapeDrawable) // 确保布局开启裁剪 shapedLayout.clipToPadding = true shapedLayout.clipChildren = true
方案二:自定义ClipPath实现(大斜角场景)
如果需要的是类似参考图的大斜角(从右下角向左上方切割),用自定义裁剪路径更灵活:
shapedLayout.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { shapedLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) val path = Path() // 绘制裁剪路径:左上→右上→右下→(斜角终点)→左下→闭合 path.moveTo(0f, 0f) path.lineTo(shapedLayout.width.toFloat(), 0f) path.lineTo(shapedLayout.width.toFloat(), shapedLayout.height.toFloat()) // 这里的offset是斜角的水平偏移量,可根据需求调整(示例为100px) val offset = 100f path.lineTo(offset, shapedLayout.height.toFloat()) path.lineTo(0f, shapedLayout.height.toFloat()) path.close() // 应用裁剪路径 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { shapedLayout.clipToOutline = true shapedLayout.outline = object : Outline() { init { setConvexPath(path) } } } else { shapedLayout.clipPath = path } // 设置布局背景为白色 shapedLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.white)) } }) // 辅助工具方法:dp转像素 fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
内容的提问来源于stack exchange,提问作者Taki
相关产品推荐
相关产品推荐

