Как обрезать Drawables с XML-файлами? - PullRequest
0 голосов
/ 16 сентября 2018

Я пытаюсь создать оверлей для углов в моем приложении.Я хочу, чтобы они были круглыми и черными все время вот так:

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>

Затем я добавил ее в свою тему в качестве андроида: windowFrame:

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

Но, очевидно, тогда все было белым.Теперь я пытаюсь обрезать вторую фигуру вместо того, чтобы окрашивать ее в белый цвет, и если это не сработает, я ищу другой способ заставить работать мой угловой оверлей!

Спасибо за любую помощь!

1 Ответ

0 голосов
/ 17 сентября 2018

Вы можете создать пользовательский макет фрейма и обернуть им весь свой контент.

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). Этот режим создает магию и отсекает темный прозрачный прямоугольник от темноты.

Может быть, это поможет или, по крайней мере, подтолкнет вас в правильном направлении.

...