안드로이드

[Android] Animation Transition 시 이미지 로딩 개선하기

easyhz 2024. 4. 14. 15:58

문제

프로젝트의 앨범 상세 보기 화면에서 이미지 상세로 들어갈 때, 부드러운 연출을 위해 애니메이션을 줬다. 

그리고 성공적으로 되는듯 했으나, 가끔씩 이미지가 깜빡거리면서 보이는 현상을 발견했다. (실제 기기에서는 더 심했음)

왼쪽) 애니메이션 적용

오른쪽) 문제점 

1) 애니메이션을 적용한 화면 / 2) 문제점

 

 

왜 이런 현상이 발생할까?

상세 보기 화면(이하 A화면) 에서 이미지 상세 화면 (이하 B화면)으로 갈 때 모든 이미지 url 을 argument로 넘겨주다보니, 이미지가 로딩이 다 되지 않고 애니메이션이 이루어지기 때문에 이런 현상이 일어난 것으로 보인다. 애니메이션 시점과 이미지 로딩 시점이 일치하지 않기 때문에 발생한 것

- 처음 사진을 클릭 했을 때보다 그 아래에 나오는 사진을 클릭 했을 때 현상이 더 도드라졌다. 

 

더 자세히 분석해보자면, 이미지 로딩 시점이 일치하지 않는 이유는 메모리를 불러온 곳의 차이에 있다

메모리 캐시 -> 정삭적으로 작동

디스크 캐시 -> 문제점 발생

운영체제 캐시에 대해 잘 생각해보면 납득이 간다

캐시
Glide 캐시 작동 방식

이미지 출처

 

Best strategy to load images using Glide — Image loading library for Android

Glide is an Image Loader Library for Android developed by bumptech and is a library that is recommended by Google. It has been used in…

medium.com

 

 

간단한 해결

 해결하는 것은 로딩이 다 되면 애니메이션을 실행하는 것이다. 

// 이미지 로드
private fun ImageView.setImage(context: Context, currentItem: String) {
    Glide.with(context).load(currentItem)
        .error(R.drawable.default_image)
        .fallback(R.drawable.default_image)
        .placeholder(R.color.black)
        .listener(glideListener(currentItem))
        .into(this)
}

// 리소스가 준비됐는지 확인
private fun glideListener(currentItem: String) = object : RequestListener<Drawable> {
    override fun onLoadFailed(
        e: GlideException?,
        model: Any?,
        target: Target<Drawable>,
        isFirstResource: Boolean
    ): Boolean {
        return false
    }
    // 준비됐나요
    override fun onResourceReady(
        resource: Drawable,
        model: Any,
        target: Target<Drawable>?,
        dataSource: DataSource,
        isFirstResource: Boolean
    ): Boolean {
        onLoaded(currentItem) // 네네 선생님
        return false
    }
}

 

이제 로드한 이미지와 유저가 선택한 사진이 일치했을 때 애니메이션을 주면 된다.

// onLoaded 파라미터에 전달될 메서드
private fun startEnterTransition(currentItem: String) {
    if (args.images.current == currentItem) {
        startPostponedEnterTransition()
    }
}

 

 

 

해결!

 

 

참고자료

https://bumptech.github.io/glide/doc/caching.html

 

Glide v4 : Caching

Caching in Glide By default, Glide checks multiple layers of caches before starting a new request for an image: Active resources - Is this image displayed in another View right now? Memory cache - Was this image recently loaded and still in memory? Resourc

bumptech.github.io

https://medium.com/android-news/best-strategy-to-load-images-using-glide-image-loading-library-for-android-e2b6ba9f75b2

 

Best strategy to load images using Glide — Image loading library for Android

Glide is an Image Loader Library for Android developed by bumptech and is a library that is recommended by Google. It has been used in…

medium.com