This view allows draw operations to be executed in a different class. This makes it easier to draw onto a canvas without having to create a custom view for every different use case.
package com.pixplicity.examples.ui.view
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import java.util.*
/**
* A simple View providing a render callback to other classes.
*/
class OverlayView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val callbacks = LinkedList<DrawCallback>()
fun addCallback(callback: DrawCallback) {
callbacks.add(callback)
}
@Synchronized override fun draw(canvas: Canvas) {
super.draw(canvas)
for (callback in callbacks) {
callback.draw(canvas)
}
}
/**
* Interface defining the callback for client classes.
*/
interface DrawCallback {
fun draw(canvas: Canvas)
}
/**
* Implementation of {@link DrawCallback} that adds an 'elapsed time since last frame' parameter
*/
abstract class TimedDrawCallback : DrawCallback {
private var mPrevTimestamp: Long = -1
override fun draw(canvas: Canvas) {
val now = System.currentTimeMillis()
val timeSinceLastFrame = if (mPrevTimestamp < 0) -1 else System.currentTimeMillis() - mPrevTimestamp
mPrevTimestamp = now
draw(canvas, timeSinceLastFrame)
}
/**
*
* @param canvas The Canvas to draw on
* @param millisSinceLastFrame The time elapsed (in millis) since the last time this method was called
*/
abstract fun draw(canvas: Canvas, millisSinceLastFrame: Long)
}
}
Usage
myOverlayView.addCallback(object : TimedDrawCallback {
override fun draw(canvas: Canvas, millisSinceLastFrame: Long) {
// draw something on the canvas here
}
})