如何用xml文件剪辑drawable?

问题描述 投票:0回答:1

我正在尝试为我的应用中的角落创建叠加层。我希望它们像这样一直是圆形和黑色的:

我用这段代码创建了它:

<?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>

但显然一切都是白色的。现在我正在尝试剪裁第二个形状,而不是将其着色为白色,如果这不起作用,我正在寻找另一种方法让我的角落叠加工作!

谢谢你的帮助!

android android-layout android-drawable
1个回答
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)。这种模式可以制造魔法并从黑暗中切割出明显的矩形。

也许它会帮助或至少将你的思想推向正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.