如何使用XML文件剪切可绘制对象?

时间:2018-09-16 14:21:38

标签: android android-layout android-drawable

我正在尝试为我的应用中的角落创建一个叠加层。 我希望它们一直都是黑色的:

Attached Image

我用以下代码创建了它:

<?xml version="1.0" encoding="utf-8"?>

<item>
    <shape android:shape="rectangle">
        <solid android:color="#000"/>
    </shape>
</item>

<item>
    <shape android:shape="rectangle">
        <solid android:color="#FFF"/>
        <corners android:radius="24dp"/>
    </shape>
</item>

然后我将其作为android:windowFrame添加到主题中:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowFrame">@drawable/corner_overlay</item>
</style>

但是显然所有的东西都是白色的。现在,我试图修剪第二个形状,而不是将其着色为白色,如果那不起作用,我正在寻找另一种方法来使我的边角覆盖层起作用!

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以创建自定义框架布局,并用其包装所有内容。

class RoundedCornerLayout : FrameLayout {

private var paint: Paint? = null
private var paint2: Paint? = null
private var cornerRadius: Float = 10f

private var mWidth: Int = 0
private var mHeight: Int = 0

constructor(context: Context) : super(context) {
    init(context, null, 0)
}

constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    init(context, attrs, 0)
}

constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    init(context, attrs, defStyle)
}

private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
    val metrics = context.getResources().getDisplayMetrics()
    cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics)

    paint = Paint(Paint.ANTI_ALIAS_FLAG)
    paint?.color = Color.BLACK

    paint2 = Paint(Paint.ANTI_ALIAS_FLAG)
    paint2?.color = Color.TRANSPARENT
    paint2?.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)

    setWillNotDraw(false)
    setLayerType(LAYER_TYPE_SOFTWARE, null)
}

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
    super.onSizeChanged(w, h, oldw, oldh)
    mWidth = w
    mHeight = h
}

override fun onDraw(canvas: Canvas?) {
    canvas?.drawRect(0f, 0f, mWidth.toFloat(), mHeight.toFloat(), paint)
    canvas?.drawRoundRect(RectF(0f, 0f, mWidth.toFloat(), mHeight.toFloat()), cornerRadius, cornerRadius, paint2)
}

companion object {
    private val CORNER_RADIUS = 40.0f
}
}

并在您的xml中使用它:

<com.dantes.backstack.RoundedCornerLayout
            android:id="@+id/wrapper"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

      <!-- Your content here-->

</com.dantes.backstack.RoundedCornerLayout>

这当然是草稿,您需要对其进行优化并更加明确自己的目的。但是主要部分是PorterDuffXfermode(PorterDuff.Mode.CLEAR)。此模式可产生魔力并从黑暗中切出目标矩形。

也许会帮助或至少将您的思想朝正确的方向发展。