본문 바로가기
Android/Concepts

Glide 라이브러리 사용법

by JuHy_ 2020. 4. 30.

Glide란?

서버로부터 이미지를 받아오는 것은 여러가지 방법이 있다.

기본적으로 비트맵을 직접 받아와 띄워줄 수도 있지만 이 경우 직접 처리해야 할 것이 많다.

 

자세한 방법과 내용은 아래 글 참고.

https://ju-hy.tistory.com/68

 

서버로부터 Bitmap 이미지 받아오기

HttpURLConnection이나 Volley 라이브러리를 이용하여 http 통신으로 서버로부터 데이터를 받아올 수 있다. 하지만 이미지의 경우 용량이 크기 때문에 다른 데이터와 구분하여 다른 방식으로 받는 것이

ju-hy.tistory.com

 

따라서 구글에서는 이미지를 불러오고 관련 작업을 편하게 수행할 수 있도록 Glide 라이브러리를 제공하고 있다.

https://github.com/bumptech/glide

 

bumptech/glide

An image loading and caching library for Android focused on smooth scrolling - bumptech/glide

github.com

 

Glide를 사용하면 프로젝트 내의 drawable 이미지 뿐만 아니라 url로 이미지를 편하게 가져와 사용할 수 있다.

 

사용법

implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

먼저 gradle의 dependencies에 위 두 줄을 추가하여 라이브러리를 불러와준다.

 

<uses-permission android:name="android.permission.INTERNET" />

이미지를 url을 통해 서버로부터 받아올 것이라면 manifest에 INTERNET 권한도 추가해주자.

 

ImageView imageView = findViewById(R.id.imageView);
Glide.with(this).load(url).into(imageView);

라이브러리를 불러왔다면 먼저 이미지를 띄워줄 ImageView를 찾아온다.

그 다음 Glide에 context를 넣어주고, url을 통해 load하여 into() 함수를 통해 imageView에 넣어주면 된다.

 

ImageView imageView = rootView.findViewById(R.id.imageView);
Glide.with(getActivity()).load(url).into(imageView);

Fragment에서는 this 대신 getActivity()를 넣어주면 Activity와 똑같이 불러올 수 있다.

 

또한 기본적으로 이미지를 불러오는 기능 외에도

 

placeholder() - 이미지를 로딩하는 동안 보여줄 이미지 지정하기

thumbnail() - 이미지를 지정한 비율만큼 미리 불러와 보여주기

centerCrop() - 이미지 가운데를 기준으로 일정 크기만큼 자르기

asBitmap() - Bitmap으로 불러오기

asGif() - GIF로 불러오기

 

등의 함수를 통해 이미지 사전작업이나 조정 작업도 가능하다.

 

 

더 자세한 기능들은 Glide 공식 문서를 참고하여 구현하자.

https://bumptech.github.io/glide/doc/getting-started.html

 

Glide v4 : Getting Started

Basic Usage Loading images with Glide is easy and in many cases requires only a single line: Glide.with(fragment) .load(myUrl) .into(imageView); Cancelling loads you no longer need is simple too: Glide.with(fragment).clear(imageView); Although it’s good pr

bumptech.github.io