Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An ImageView that allows the foreground drawable to be positioned anywhere within the view's bounds by using a floating point range 0 - 1, where 0 means the left/top edge is snug with view's left/top, and 1 means the right/bottom edge is snug with view's right/bottom.. X and Y can be positioned separately.
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.ImageView
import letstwinkle.com.twinkle.R
class BetterForegroundImageView : ImageView {
constructor(ctx: Context) : super(ctx)
constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {
val a = ctx.theme.obtainStyledAttributes(attrs, R.styleable.BetterForegroundImageView, 0, 0)
try {
mForeground = a.getDrawable(R.styleable.BetterForegroundImageView_fourground)
foregroundXPos = a.getFloat(R.styleable.BetterForegroundImageView_foregroundXPos, foregroundXPos)
foregroundYPos = a.getFloat(R.styleable.BetterForegroundImageView_foregroundYPos, foregroundYPos)
} finally {
a.recycle();
}
}
var foregroundXPos = 0.5f
var foregroundYPos = 0.5f
private var mForeground: Drawable? = null
fun setFourground(fg: Drawable?) {
mForeground = fg
}
fun getFourground(): Drawable? = mForeground
private fun drawForeground(canvas: Canvas) {
val foreground = mForeground
foreground?.let {
val l = foregroundXPos * (this.width - foreground.intrinsicWidth)
val t = foregroundYPos * (this.height - foreground.intrinsicHeight)
val r = l + foreground.intrinsicWidth
val b = t + foreground.intrinsicHeight
foreground.setBounds(Math.round(l), Math.round(t), Math.round(r), Math.round(b))
foreground.draw(canvas)
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
drawForeground(canvas)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment