Animate a series of images with an image overlay.

Use case
An image overlay is useful for displaying fast and dynamic images; for example, rendering real-time sensor data captured from a drone. Each frame from the drone becomes a static image which is updated on the fly as the data is made available.
How to use the sample
The application loads a map of the Southwestern United States. Tap the “Start” or “Stop” button to toggle the radar animation. Use the drop down menu to select how quickly the animation plays. Move the slider to change the opacity of the image overlay.
How it works
- Create an
ImageOverlayand add it to theSceneView. - Set up a timer with an initial interval time of 17ms, which will display approximately 60
ImageFrames per second. - On every tick of the timer, add the next image frame to the image overlay.
Relevant API
- ImageFrame
- ImageOverlay
- SceneView
About the data
These radar images were captured by the US National Weather Service (NWS). They highlight the Pacific Southwest sector which is made up of part the western United States and Mexico. For more information visit the National Weather Service website.
Additional information
The supported image formats are GeoTIFF, TIFF, JPEG, and PNG. ImageOverlay does not support the rich processing and rendering capabilities of a RasterLayer. Use Raster and RasterLayer for static image rendering, analysis, and persistence.
This sample uses the GeoViewCompose Toolkit module to implement a Composable MapView.
Tags
3d, animation, drone, dynamic, image frame, image overlay, real time, rendering
Sample Code
/* Copyright 2024 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.animateimageswithimageoverlay
import android.content.Intentimport android.os.Bundleimport com.esri.arcgismaps.sample.sampleslib.DownloaderActivity
class DownloadActivity : DownloaderActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) downloadAndStartSample( Intent(this, MainActivity::class.java), // get the app name of the sample getString(R.string.animate_images_with_image_overlay_app_name), listOf( // ArcGIS Portal item containing the zip of Reflectivity radar images. "https://www.arcgis.com/home/item.html?id=9465e8c02b294c69bdb42de056a23ab1" ) ) }}/* Copyright 2024 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.animateimageswithimageoverlay
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composableimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.esri.arcgismaps.sample.animateimageswithimageoverlay.screens.AnimateImagesWithImageOverlayScreenimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN)
enableEdgeToEdge() setContent { SampleAppTheme { AnimateImagesWithImageOverlayApp() } } }
@Composable private fun AnimateImagesWithImageOverlayApp() { Surface(color = MaterialTheme.colorScheme.background) { AnimateImagesWithImageOverlayScreen( sampleName = getString(R.string.animate_images_with_image_overlay_app_name) ) } }}/* Copyright 2024 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.animateimageswithimageoverlay.components
import android.app.Applicationimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.Pointimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISSceneimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.view.Cameraimport com.arcgismaps.mapping.view.ImageFrameimport com.arcgismaps.mapping.view.ImageOverlayimport com.esri.arcgismaps.sample.animateimageswithimageoverlay.Rimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launchimport java.io.Fileimport java.util.Timerimport kotlin.concurrent.fixedRateTimer
class AnimateImagesWithImageOverlayViewModel(application: Application) : AndroidViewModel(application) {
private val provisionPath: String by lazy { application.getExternalFilesDir(null)?.path.toString() + File.separator + application.getString( R.string.animate_images_with_image_overlay_app_name ) }
// Get the folder path containing all the image overlays private val filePath = "$provisionPath/PacificSouthWest"
var opacity by mutableFloatStateOf(1.0f) private set
fun updateOpacity(opacityFromSlider: Float) { opacity = opacityFromSlider imageOverlay.opacity = opacity }
val fpsOptions = listOf(60, 30, 15) private val _fps = MutableStateFlow(fpsOptions[1]) val fps = _fps.asStateFlow()
fun updateFpsOption(fpsIndex: Int) { _fps.value = fpsOptions[fpsIndex] }
var isStarted by mutableStateOf(true) private set
fun updateIsStarted(isStartedFromButton: Boolean) { isStarted = isStartedFromButton toggleAnimationTimer() }
// Create an envelope of the pacific southwest sector for displaying the image frame private val pointForImageFrame = Point( x = -120.0724, y = 35.1310, spatialReference = SpatialReference.wgs84() ) private val pacificSouthwestEnvelope = Envelope( center = pointForImageFrame, width = 15.0958, height = -14.3770 )
// Create a scene with the dark gray basemap and elevation source val arcGISScene by mutableStateOf(ArcGISScene(BasemapStyle.ArcGISDarkGray).apply { // Create a camera, looking at the pacific southwest sector val observationPoint = Point(-116.621, 24.7773, 856977.0) val camera = Camera(observationPoint, 353.994, 48.5495, 0.0) initialViewpoint = Viewpoint(pacificSouthwestEnvelope, camera) })
// Create a message dialog view model for handling error messages val messageDialogVM = MessageDialogViewModel()
// Keep track of the list of image frames added in cache private var imageFrames = mutableListOf<ImageFrame>()
// Keep track of the image frame currently in view private var imageFrameIndex = 0
// Timer task to customize frame rates private var timer: Timer? = null
var imageOverlay = ImageOverlay() private set
init {
// Get the image files from local storage (File(filePath).listFiles())?.sorted()?.forEach { imageFile -> // Create an image with the given path and use it to create an image frame val imageFrame = ImageFrame(imageFile.path, pacificSouthwestEnvelope) imageFrames.add(imageFrame) } // Set the initial image frame to image overlay imageOverlay.imageFrame = imageFrames[imageFrameIndex]
viewModelScope.launch { arcGISScene.load().onFailure { error -> messageDialogVM.showMessageDialog( "Failed to load map", error.message.toString() ) }
// On changes to the fps, create a new timer _fps.collect { if (isStarted) { createNewTimer() } } }
// Start the animation timer createNewTimer() }
/** * Create a new image frame from the image at the current index and add it to the image overlay. */ private fun addNextImageFrameToImageOverlay() { // Set image frame to image overlay imageOverlay.imageFrame = imageFrames[imageFrameIndex] // Increment the index to keep track of which image to load next imageFrameIndex++ // Reset index once all files have been loaded if (imageFrameIndex == imageFrames.size) imageFrameIndex = 0 }
/** * Create a new timer for the given period which repeatedly calls [addNextImageFrameToImageOverlay].. */ private fun createNewTimer() { // Get the current period from the fps state flow val period = when (_fps.value) { 60 -> 17 // 1000ms/17 = 60 fps 30 -> 33 // 1000ms/33 = 30 fps 15 -> 67 // 1000ms/67 = 15 fps else -> 0 } // Cancel any timers that might be running timer?.cancel() timer = null // Create a new timer with the given period timer = fixedRateTimer("Image overlay timer", period = period.toLong()) { addNextImageFrameToImageOverlay() } }
/** * Toggles starting and stopping the timer on button tap. */ private fun toggleAnimationTimer() { timer?.let { // Cancel any running timer timer?.cancel() timer = null // Change the start/stop button to "start" isStarted = false } ?: run { createNewTimer() // Change the start/stop button to "stop" isStarted = true } }}/* Copyright 2024 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.animateimageswithimageoverlay.screens
import android.content.res.Configurationimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.wrapContentHeightimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Settingsimport androidx.compose.material3.Buttonimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.ExposedDropdownMenuBoximport androidx.compose.material3.ExposedDropdownMenuDefaultsimport androidx.compose.material3.FloatingActionButtonimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.MenuAnchorTypeimport androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Sliderimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Textimport androidx.compose.material3.TextFieldimport androidx.compose.material3.rememberModalBottomSheetStateimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.toolkit.geoviewcompose.SceneViewimport com.esri.arcgismaps.sample.animateimageswithimageoverlay.components.AnimateImagesWithImageOverlayViewModelimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport kotlin.math.roundToInt
/** * Main screen layout for the sample app */@OptIn(ExperimentalMaterial3Api::class)@Composablefun AnimateImagesWithImageOverlayScreen(sampleName: String) { val sceneViewModel: AnimateImagesWithImageOverlayViewModel = viewModel() // Set up the bottom sheet controls val controlsBottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var isBottomSheetVisible by remember { mutableStateOf(false) } LaunchedEffect(isBottomSheetVisible) { when { isBottomSheetVisible -> controlsBottomSheetState.show() else -> controlsBottomSheetState.hide() } }
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, floatingActionButton = { if (!isBottomSheetVisible) { FloatingActionButton( modifier = Modifier.padding(bottom = 36.dp, end = 12.dp), onClick = { isBottomSheetVisible = true } ) { Icon(Icons.Filled.Settings, contentDescription = "Show ImageOverlay menu") } } }, content = { Column( modifier = Modifier .fillMaxSize() .padding(it) ) { SceneView( modifier = Modifier .fillMaxSize(), arcGISScene = sceneViewModel.arcGISScene, imageOverlays = listOf(sceneViewModel.imageOverlay) ) if (isBottomSheetVisible) { ModalBottomSheet( modifier = Modifier.wrapContentHeight(), sheetState = controlsBottomSheetState, onDismissRequest = { isBottomSheetVisible = false } ) { ImageOverlayMenu( isStarted = sceneViewModel.isStarted, fps = sceneViewModel.fps.collectAsState().value, opacity = sceneViewModel.opacity, fpsOptions = sceneViewModel.fpsOptions, onFpsOptionSelected = sceneViewModel::updateFpsOption, onOpacityChanged = sceneViewModel::updateOpacity, onIsStartedChanged = sceneViewModel::updateIsStarted ) } } sceneViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } })}
@OptIn(ExperimentalMaterial3Api::class)@Composableprivate fun ImageOverlayMenu( isStarted: Boolean, fps: Int, opacity: Float, fpsOptions: List<Int>, onFpsOptionSelected: (Int) -> Unit, onOpacityChanged: (Float) -> Unit, onIsStartedChanged: (Boolean) -> Unit) {
Column( modifier = Modifier .fillMaxWidth() .padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Image overlay options", style = MaterialTheme.typography.headlineSmall )
HorizontalDivider()
Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Opacity:", style = MaterialTheme.typography.labelLarge ) Text( text = (opacity * 100).roundToInt().toString() + "%", style = MaterialTheme.typography.labelLarge ) }
// Opacity Slider Slider( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp), value = opacity, onValueChange = { onOpacityChanged(it) }, valueRange = 0f..1.0f )
Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { // FPS Dropdown Menu var expanded by remember { mutableStateOf(false) } ExposedDropdownMenuBox( modifier = Modifier.width(150.dp), expanded = expanded, onExpandedChange = { expanded = !expanded } ) { TextField( value = "$fps fps", onValueChange = {}, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable) ) ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { fpsOptions.forEachIndexed { index, fps -> DropdownMenuItem( text = { Text("$fps fps") }, onClick = { onFpsOptionSelected(index) expanded = false }) // Show a divider between dropdown menu options if (index < fpsOptions.lastIndex) { HorizontalDivider() } } } }
// Start/Stop Button Button(onClick = { onIsStartedChanged(!isStarted) }) { Text(if (isStarted) "Stop" else "Start") } } }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun ClusterInfoContentPreview() { SampleAppTheme { Surface { ImageOverlayMenu( isStarted = true, fps = 60, opacity = 1F, fpsOptions = listOf(60, 30, 15), onFpsOptionSelected = { }, onOpacityChanged = { }, onIsStartedChanged = { } ) } }}