Skip to content

Instantly share code, notes, and snippets.

@grandstaish
Created July 16, 2020 14:36
Show Gist options
  • Save grandstaish/84d00ccc4af25175187e052e6f518ea2 to your computer and use it in GitHub Desktop.
Save grandstaish/84d00ccc4af25175187e052e6f518ea2 to your computer and use it in GitHub Desktop.
/**
* Sets a background drawable on this view that will draw a slice of [ancestor]'s background that sits underneath
* this view. This is useful when [ancestor] has a gradient background and you want another child to seamlessly
* continue that gradient while also having an opaque background to allow for elevation.
*/
fun View.setBackgroundFromAncestor(ancestor: ViewGroup) {
check(ancestor.isAncestorOf(this))
if (ancestor.background == null) return
background = CopyBackgroundDrawable(this, ancestor)
}
private class CopyBackgroundDrawable(private val view: View, private val ancestor: ViewGroup) : Drawable() {
private val outRect = Rect()
override fun draw(canvas: Canvas) {
val background = ancestor.background ?: return
ancestor.offsetDescendantRect(view, outRect)
val offsetX = outRect.left.toFloat()
val offsetY = outRect.top.toFloat()
canvas.withTranslation(-offsetX, -offsetY) { background.draw(canvas) }
}
override fun getOutline(outline: Outline) {
super.getOutline(outline)
outline.alpha = 1f
}
override fun setAlpha(alpha: Int) {}
override fun getOpacity(): Int = OPAQUE
override fun setColorFilter(colorFilter: ColorFilter?) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment