本文主要是介绍【Android高级UI】将View或Layout裁剪为任意形状,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求
-
将View裁剪为指定形状
-
将Layout裁剪为指定形状,并且Children不能超过裁剪范围
应用
- 圆角图片
- 异形图片
- 圆角Layout
方案
通过ViewOutlineProvider裁剪控件范围
实现
fun View.getMeasureSize(): Size {val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)measure(widthSpec, heightSpec)return Size(measuredWidth, measuredHeight)
}fun View.clipToRoundRect(cornerRadius: Number) {outlineProvider = object : ViewOutlineProvider() {override fun getOutline(view: View, outline: Outline) {val measuredSize = view.getMeasureSize()outline.setRoundRect(0, 0, measuredSize.width, measuredSize.height, cornerRadius.toFloat())}}setClipToOutline(true)if (this is ViewGroup) {clipChildren = true}
}
这篇关于【Android高级UI】将View或Layout裁剪为任意形状的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!