Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Kotlin-First 's Picture loading Library

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to use Kotlin-First 's picture loading library". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The origin of the name Coil: from the initials of Coroutine Image Loader, you can see that the image is loaded through the Kotlin co-program. The features are as follows:

Faster: Coil has many performance optimizations, including memory cache and disk cache, keeping thumbnails in memory, recycling Bitmap through BitmapPool, automatically pausing and canceling network requests, etc.

More lightweight: Coil has only 2000 methods, about the same number as Picasso, and much lighter than Glide and Fresco

Easier to use: Coil's API takes full advantage of the new features of Kotlin and has rich extension functions that simplify and reduce a lot of boilerplate code

More popular: Coil is developed through Kotlin and uses many popular open source libraries, including Coroutines, okhttp, okio, and AndroidX Lifecycles

As can be seen from the features of Coil, this is a very suitable image loading library for personal App, especially App developed by pure Kotlin. And Coil uses a large number of new features and cooperative programs of Kotlin, which is of great value for us to learn Kotlin. Compared with glide and fresco, which have a very complex structure and an amazing amount of code, Coil has only about 2000 methods, so it is also very suitable for source code research and learning.

Basic use

Coil can be downloaded from mavenCentral ():

Implementation ("io.coil-kt:coil:1.1.1")

Coil adds a lot of extension functions to ImageView, so we can load images with one line of code:

/ / URL imageView.load ("https://www.example.com/image.jpg") / / Resource imageView.load (R.drawable.image) / / File imageView.load (File (" / path/to/image.jpg "))

At the same time, we can also use lambda syntax to easily configure image loading:

ImageView.load ("https://www.example.com/image.jpg") {crossfade (true) placeholder (R.drawable.image) transformations (CircleCropTransformation ())} commonly used APIImageLoader

ImageLoader is the butler of image loading in Coil, and is responsible for caching, data acquisition, image decoding, request management, Bitmap cache pool, memory management, and so on. It is generally recommended that you only create an ImageLoader and share it in App, so the performance is optimal. This is because each ImageLoader has its own memory cache and Bitmap cache pool.

We can create and configure ImageLoader through the constructor.

Val imageLoader = ImageLoader.Builder (context). PopulableMemoryPercentage (0.25). Crossfade (true). Build ()

At the same time, because ImageLoader is an interface, it means that it is very convenient for us to test, for example, we can inject an ImageLoader of fake to return the same drawable every time.

Val fakeImageLoader = object: ImageLoader {privateval drawable = ColorDrawable (Color.BLACK) override fun enqueue (request: ImageRequest): Disposable {request.target?.onStart (drawable) request.target?.onSuccess (drawable) return disposable} override suspend fun execute (request: ImageRequest): ImageResult {return SuccessResult (drawable = drawable, request = request) Metadata = ImageResult.Metadata (memoryCacheKey = MemoryCache.Key (""), isSampled = false, dataSource = DataSource.MEMORY_CACHE, isPlaceholderMemoryCacheKeyPresent = false)}} ImageRequest

ImageRequest provides all the necessary information for ImageLoader to load images, and we can also use custom Target for processing.

Val request = ImageRequest.Builder (context) .data ("https://www.example.com/image.jpg") .target {drawable-> / / Handle the result. } .build () context.imageLoader.enqueue (request)

ImageRequest is created based on Builder mode and contains various configuration items for loading images. Here we focus on the most commonly used configuration items.

Disposable

Disposable is the return value after calling the load () method, which is mainly used to cancel the image loading:

Interface Disposable {/ * if the image load request has been completed or cancelled, return true * / val isDisposed: Boolean / * cancel the ongoing image load request and release related resources And the method is idempotent * / fun dispose () / * non-blocking waiting for the end of the task * / @ ExperimentalCoilApi suspend fun await ()} picture transformation

Image transformation is a very common function in the picture loading library. Coil abstracts it into a Transformation interface. You can see that there is a BitmapPool parameter in the transform () method. This is because a Bitmap is often needed to implement the graphic transformation, which can be obtained directly in the BitmapPool, thus reusing the existing Bitmap.

Interface Transformation {fun key (): String suspend fun transform (pool: BitmapPool, input: Bitmap, size: Size): Bitmap} imageView.load ("https://www.example.com/image.jpg") {transformations (CircleCropTransformation ())})

Coil mainly provides the effects of these image transformations:

Function expansion

On the basis of providing many necessary functions, Coil has reserved a lot of expansion points for developers to implement customization. The image loading of Coil mainly includes four main modules:

Interceptors

Coil's Interceptor undoubtedly draws lessons from the design idea of okhttp, which greatly facilitates the subsequent feature expansion. For example, we can add a custom cache layer to Coil:

Class CustomCacheInterceptor (privateval context: Context, privateval cache: LruCache): Interceptor {override suspend fun intercept (chain: Interceptor.Chain): ImageResult {val value = cache.get (chain.request.data.toString ()) if (value! = null) {return SuccessResult (drawable = value.bitmap.toDrawable (context), request = chain.request Metadata = TODO ()} return chain.proceed (chain.request)}} Mappers, Fetchers

When load () is called externally, the String parameter passed in may point to either the local resource file or the network picture. Mappers and Fetchers are used together to distinguish the resource types, for example:

ImageView.load ("android.resource://example.package.name/drawable/image") imageView.load ("https://www.example.com/image.jpg")")

StringMapper converts the incoming String to the corresponding Uri.

Internal class StringMapper: Mapper {override fun map (data: String) = data.toUri ()}

ResourceUriFetcher determines whether the scheme type of Uri is android.resource, which represents the local resource file, while HttpUriFetcher determines whether the scheme of Uri is http or https, and if so, it represents network images.

Internal class HttpUriFetcher (callFactory: Call.Factory): HttpFetcher (callFactory) {override fun handles (data: Uri) = data.scheme = = "http" | | data.scheme = = "https" override fun key (data: Uri) = data.toString () override fun Uri.toHttpUrl (): HttpUrl = HttpUrl.get (toString ())}

Decoders

Android supports many image formats, but there are also many formats that it does not support (for example, Gif, SVG, video frames, etc.), so Coil provides a corresponding extension library.

① Gif (GifDecoder supports all API levels, but slow, and ImageDecoderDecoder loads fast But only available on API 28 and later) implementation ("io.coil-kt:coil-gif:1.1.1") val imageLoader = ImageLoader.Builder (context) .principentRegistry {if (SDK_INT > = 28) {add (ImageDecoderDecoder ())} else {add (GifDecoder ())} .build () ② SVG (if the requested MIME type is image/svg+xml Will automatically detect and decode all SVG) implementation ("io.coil-kt:coil-svg:1.1.1") val imageLoader = ImageLoader.Builder (context) .principentRegistry {add (SvgDecoder (context))} .build () ③ video frames (only File and Uri are supported) implementation ("io.coil-kt:coil-video:1.1.1") val imageLoader = ImageLoader.Builder (context) .principentRegistry { Add (VideoFrameFileFetcher ()) add (VideoFrameUriFetcher ())} .build () "how to use Kotlin-First 's Picture load Library" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report