Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to show images downloaded from network efficiently? #210

Open
shafayatb opened this issue Sep 29, 2022 · 7 comments
Open

How to show images downloaded from network efficiently? #210

shafayatb opened this issue Sep 29, 2022 · 7 comments
Labels
priority: p4 An issue that should be addressed eventually. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design.

Comments

@shafayatb
Copy link

Basically what I am doing is downloading the images from server and making an icon with the icon generator. After all the icons has been fully generated then I am putting the markers in the map. But from large list of markers it will take too much time to draw the markers. So how to do this in an optimized way?

fun CustomMarker(
    blipsList: List<Blip>,
    iconMap: MutableMap<String, Bitmap>,
    hasImageLoaded: Boolean,
    event: (HomeEvents) -> Unit,
    markerClick: (blipId: String) -> Unit
) {
    val context = LocalContext.current
    val iconGenerator = IconGenerator(context)
    val inflatedView = View.inflate(context, R.layout.custom_marker, null)
    val userImage = inflatedView.findViewById<ImageView>(R.id.userImageView)

    iconGenerator.setBackground(null)
    iconGenerator.setContentView(
        inflatedView
    )
    for (blip in blipsList) {
        Glide.with(LocalContext.current)
            .asDrawable()
            .circleCrop()
            .load("${Constants.BASE_URL}${blip.user.photo}")
            .into(object : CustomTarget<Drawable>() {
                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    val resource =
                        AppCompatResources.getDrawable(context, R.drawable.person)?.toBitmap()
                    val circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.resources, resource)
                    circularBitmapDrawable.isCircular = true
                    userImage.setImageDrawable(circularBitmapDrawable)
                    iconMap[blip.id] = iconGenerator.makeIcon()
                    if (iconMap.size == blipsList.size) {
                        event(
                            HomeEvents.UserImageLoadedEvent(
                                true
                            )
                        )
                    }
                }

                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    userImage.setImageDrawable(resource)
                    iconMap[blip.id] = iconGenerator.makeIcon()
                    if (iconMap.size == blipsList.size) {
                        event(
                            HomeEvents.UserImageLoadedEvent(
                                true
                            )
                        )
                    }
                }

                override fun onLoadCleared(placeholder: Drawable?) {

                }

            })
    }
    if (hasImageLoaded) {
        for ((i, blip) in blipsList.withIndex()) {
            Marker(
                state = MarkerState(
                    LatLng(blip.lat, blip.lng)
                ),
                icon = BitmapDescriptorFactory.fromBitmap(
                    iconMap[blip.id] ?: iconGenerator.makeIcon()
                ),
                tag = i,
                onClick = { mark ->
                    Log.v("Blip", blipsList[mark.tag as Int].id)
                    markerClick.invoke(blipsList[mark.tag as Int].id)
                    return@Marker true
                }
            )
        }
    }
}

I tried to recompose the markers each time the image is downloaded but it got stuck in infinite recompose.

@shafayatb shafayatb added triage me I really want to be triaged. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design. labels Sep 29, 2022
@shafayatb
Copy link
Author

Use clustering

How will clustering help in this situation?

@ek868
Copy link

ek868 commented Oct 25, 2022

I have this exact same issue.

Did you end up finding any solutions?

@shafayatb
Copy link
Author

No. Enabled disk caching so next time it won't take much time. Also i am not using large images in the markers.

@stale
Copy link

stale bot commented Jun 18, 2023

This issue has been automatically marked as stale because it has not had recent activity. Please comment here if it is still valid so that we can reprioritize. Thank you!

@stale stale bot added the stale label Jun 18, 2023
@kikoso kikoso added priority: p4 An issue that should be addressed eventually. and removed triage me I really want to be triaged. labels Jul 10, 2023
@stale stale bot removed stale labels Jul 10, 2023
@cwsiteplan
Copy link

rendering async images is still a problem i think.
also see recent discussion in #385

@cwsiteplan
Copy link

using a key to trigger re-composition of the marker when the image is loaded does not work for me. (using coil)

var showImage by remember {
    mutableStateOf(false)
}

val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
        .data("https://www.aquasafemine.com/wp-content/uploads/2018/06/dummy-man-570x570.png")
        .size(Size.ORIGINAL) // Set the target size to load the image at.
        .build()
)

if (painter.state is AsyncImagePainter.State.Success) {
    showImage = true
}


MarkerComposable(
    keys = arrayOf(showImage),
    state = singapore4State,
) {
    Image(
        painter = painter,
        contentDescription = "asdf"
    )

}

@leinardi
Copy link

leinardi commented Dec 14, 2023

I've found out that using clustering plus the NonHierarchicalViewBasedAlgorithm as algorithm for the ClusterManager helps since it will render the images only for unclustered items that are visible on the screen.

    var mapSize by remember { mutableStateOf(IntSize.Zero) }

    GoogleMap(
        modifier = Modifier
            .fillMaxSize()
            .onGloballyPositioned { mapSize = it.size },
        cameraPositionState = cameraPositionState,
    ) {
        val coroutineScope = rememberCoroutineScope()
        if (!state.mapItems.isNullOrEmpty()) {
            val clusterManager = rememberClusterManager<CollaboratorsMapItem>()
            val renderer = rememberClusterRenderer(
                clusterContent = null,
                clusterItemContent = { item ->
                    AndroidView(
                        factory = { context ->
                            ImageView(context).apply {
                                scaleType = ImageView.ScaleType.CENTER_CROP
                                layoutParams = ViewGroup.LayoutParams(56.toPxSize, 56.toPxSize)
                                load(item.collaborator.imageUrl) {
                                    allowHardware(false)
                                    crossfade(false)
                                    error(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                    fallback(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                    placeholder(com.veeva.link.library.ui.R.drawable.ui_img_default_profile)
                                }
                            }
                        },
                        modifier = Modifier
                            .size(56.dp)
                            .border(3.dp, MaterialTheme.colorScheme.surface.copy(alpha = ContentAlpha.medium), CircleShape)
                            .padding(3.dp)
                            .clip(CircleShape),
                    )
                },
                clusterManager = clusterManager,
            )
            SideEffect {
                clusterManager ?: return@SideEffect
                clusterManager.algorithm = NonHierarchicalViewBasedAlgorithm(mapSize.width.toDp.roundToInt(), mapSize.height.toDp.roundToInt())
            }
            SideEffect {
                if (clusterManager?.renderer != renderer && renderer != null) {
                    (renderer as DefaultClusterRenderer).minClusterSize = 2
                    clusterManager?.renderer = renderer
                }
            }

            if (clusterManager != null) {
                Clustering(
                    items = state.mapItems,
                    clusterManager = clusterManager,
                )
            }
        }
    }

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority: p4 An issue that should be addressed eventually. type: feature request ‘Nice-to-have’ improvement, new feature or different behavior or design.
Projects
None yet
Development

No branches or pull requests

5 participants