Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Workaround to use AnimatedVectorDrawable as marker icon on Google Maps SDK.
class AnimatedVectorDrawableMarkerIcon(
marker: Marker,
private val avd: AnimatedVectorDrawableCompat,
width: Int = avd.intrinsicWidth,
height: Int = avd.intrinsicHeight
) {
private val handler = Handler(Looper.getMainLooper())
private val invalidateTask = Runnable { avd.invalidateSelf() }
private var isRunning = false
private var isAutoLoop = false
init {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
avd.setBounds(0, 0, width, height)
val callback = object : Drawable.Callback {
private var isDrawing = false
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
handler.postAtTime(what, `when`)
}
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
handler.removeCallbacks(what)
}
override fun invalidateDrawable(d: Drawable) {
if (isDrawing) return
isDrawing = true
bitmap.eraseColor(Color.TRANSPARENT)
avd.draw(Canvas(bitmap))
marker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap))
isDrawing = false
handler.postDelayed(invalidateTask, 0L)
}
}
avd.callback = callback
avd.registerAnimationCallback(object : Animatable2Compat.AnimationCallback() {
override fun onAnimationStart(drawable: Drawable?) {
drawable?.callback = callback
}
override fun onAnimationEnd(drawable: Drawable?) {
handler.removeCallbacks(invalidateTask)
if (!isAutoLoop) isRunning = false
if (isRunning) avd.start()
}
})
}
fun start(autoLoop: Boolean = true) {
isAutoLoop = autoLoop
isRunning = true
avd.start()
}
fun stop() {
isRunning = false
handler.removeCallbacks(invalidateTask)
avd.stop()
}
}
fun Marker.setAnimatedVectorDrawableIcon(
avd: AnimatedVectorDrawableCompat,
width: Int = avd.intrinsicWidth,
height: Int = avd.intrinsicHeight
) = AnimatedVectorDrawableMarkerIcon(this, avd, width, height)
val marker = map.addMarker(options)
val animatedIcon = marker.setAnimatedVectorDrawableIcon(AnimatedVectorDrawableCompat.create(...)!!)
animatedIcon.start()
// Don't forget to stop animation!
override fun onDestroyView() {
super.onDestroyView()
animatedIcon.stop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment