Translations: 简体中文
Scheme | Description | Create Function |
---|---|---|
http://, https:// | File in network | _ |
/, file:// | File in SDCard | newFileUri() |
content:// | Content Resolver | _ |
asset:// | Asset Resource | newAssetUri() |
android.resource:// | Android Resource | newResourceUri() |
data:image/, data:img/ | Base64 | newBase64Uri() |
app.icon:// | App Icon | newAppIconUri() |
The
Create Function
column in the table above shows the convenient creation function that Sketch provides for some URIs
Each URI has its own Fetcher to support it, see more about Fetcher and how to extend new URIs
Format | API Limit | Dependency module |
---|---|---|
jpeg | _ | _ |
png | _ | _ |
bmp | _ | _ |
webp | _ | _ |
svg | _ | sketch-svg |
heif | Android 9+ | _ |
gif | _ | sketch-gif sketch-gif-koral |
webp Animated | Android 9+ | _ |
heif Animated | Android 11+ | _ |
video frames | _ | sketch-video sketch-video-ffmpeg |
Each image type has a corresponding Decoder support for it, see more about Decoder and how to extend new image types
The Sketch class is used to execute ImageRequest and handle image downloading, caching, decoding, transformation, request management, memory management, and more.
By default, it is recommended to rely on the 'sketch' module, which provides a singleton of Sketch as well as some handy extension functions
In singleton mode, you can get Sketch through the Context's extension function, as follows:
val sketch = context.sketch
Method 1: Implement the SketchFactory interface on the Application class to create and configure Sketch as follows:
class MyApplication : Application(), SketchFactory {
override fun createSketch(): Sketch {
return Sketch.Builder(this).apply {
logger(Logger(DEBUG))
httpStack(OkHttpStack.Builder().build())
}.build()
}
}
Method 2: Create and configure Sketch and set it up as a singleton via the ' SketchSingleton.setSketch()' method, as follows:
val sketch = Sketch.Builder(context).apply {
logger(Logger(DEBUG))
httpStack(OkHttpStack.Builder().build())
}.build()
SketchSingleton.setSketch(sketch)
// or
SketchSingleton.setSketch(SketchFactory {
Sketch.Builder(context).apply {
logger(Logger(DEBUG))
httpStack(OkHttpStack.Builder().build())
}.build()
})
If you don't want to use the singleton pattern, you can rely on the 'sketch-core' module and then use the Sketch. Builder creates an instance of Sketch as follows:
val sketch = Sketch.Builder(context).apply {
logger(Logger(DEBUG))
httpStack(OkHttpStack.Builder().build())
}.build()
For more configurable parameters, please refer to Sketch.Builder class
The ImageRequest interface defines all the parameters required to display the image, such as uri, target, conversion configuration, resizing, and so on.
There are three types of ImageRequest:
- DisplayRequest: The result of the request is Drawable, which is used to display the picture to ImageView, RemoteView, or Compose Painter
- LoadRequest: The result of the request is Bitmap, which is used in scenarios where Bitmap needs to be manipulated directly, memory caching is not supported, and all GIFs will be decoded into static images
- DownloadRequest: The result of the request is DiskCache.Snapshot or ByteArray for downloading images in advance or for direct access to image files
In the case of DisplayRequest, the other two are much the same
Build with Builder:
val request = DisplayRequest.Builder(context, "https://www.example.com/image.jpg")
.placeholder(R.drawable.image)
.transformations(CircleCropTransformation())
.target(imageView)
.build()
Build with a function of the same name:
val request = DisplayRequest(context, "https://www.example.com/image.jpg") {
placeholder(R.drawable.image)
transformations(CircleCropTransformation())
target(imageView)
}
// or
val request1 = DisplayRequest(imageView, "https://www.example.com/image.jpg") {
placeholder(R.drawable.image)
transformations(CircleCropTransformation())
}
This can be done through the chained method provided by DisplayRequest.Builder or the trailing lambda provided by the function of the same name For configuration requests, please refer to DisplayRequest for more configuration parameters. Builder class
In singleton mode, you can hand over ImageRequest to Sketch for execution via the provided extension function enqueue() or execute():
/*
* Put an ImageRequest into a task queue, execute asynchronously on a background thread, and return a Disposable
*/
val request1 = DisplayRequest(imageView, "https://www.example.com/image.jpg")
request1.enqueue()
/*
* Place an ImageRequest in a task queue, execute asynchronously on a background thread,
* and wait for the return result in the current coroutine
*/
val request2 = DisplayRequest(context, "https://www.example.com/image.jpg")
coroutineScope.launch(Dispatchers.Main) {
val result: DisplayResult = request2.execute()
imageView.setImageDrawable(result.drawable)
}
In non-singleton mode, you need to create your own Sketch instance and execute the request through its enqueue() or execute() method:
val sketch = Sketch.Builder(context).build()
/*
* Put an ImageRequest into a task queue, execute asynchronously on a background thread, and return a Disposable
*/
val request1 = DisplayRequest(imageView, "https://www.example.com/image.jpg")
sketch.enqueue(request1)
/*
* Place an ImageRequest in a task queue, execute asynchronously on a background thread,
* and wait for the return result in the current coroutine
*/
val request2 = DisplayRequest(context, "https://www.example.com/image.jpg")
coroutineScope.launch(Dispatchers.Main) {
val result: DisplayResult = sketch.execute(request2)
imageView.setImageDrawable(result.drawable)
}
Sketch will hand the result to the DisplayRequest target to display the Drawable, and if the target is not set, you will need to actively obtain the result to process it
When a request is executed using the enqueue() method, the result can be obtained by returning Disposable.job, as follows:
val request = DisplayRequest(context, "https://www.example.com/image.jpg")
val disposable = request.enqueue()
coroutineScope.launch(Dispatchers.Main) {
val result: DisplayResult = disposable.job.await()
imageView.setImageDrawable(result.drawable)
}
When you use the execute() method to execute a request, you can get the result directly, as follows:
val request = DisplayRequest(context, "https://www.example.com/image.jpg")
coroutineScope.launch(Dispatchers.Main) {
val result: DisplayResult = request.execute()
imageView.setImageDrawable(result.drawable)
}
ImageRequest is automatically canceled in the following cases:
- request.lifecycle changes to DESTROYED state
- request.target is a ViewDisplayTarget and view's onViewDetachedFromWindow() method is executed
Executing a request using the enqueue() method returns a Disposable that can be used to cancel the request, as follows:
val disposable = DisplayRequest(imageView, "https://www.example.com/image.jpg").enqueue()
// Cancel the request when you need to
disposable.dispose()
When a request is executed using the execute() method, it can be canceled by the job of its coroutine, as follows:
val job = coroutineScope.launch(Dispatchers.Main) {
val result: DisplayResult = DisplayRequest(context, "https://www.example.com/image.jpg")
.execute()
imageView.setImageDrawable(result.drawable)
}
// Cancel the request when you need to
job.cancel()
Sketch provides a series of extensions to ImageView, as follows:
Available only in singleton mode
displayImage() extension function to display the image pointed to by the URI onto the ImageView
imageView.displayImage("https://www.example.com/image.jpg")
The above call is equivalent to:
DisplayRequest(imageView, "https://www.example.com/image.jpg").enqueue()
You can also configure parameters via the lambda trailing with the displayImage function:
imageView.displayImage("https://www.example.com/image.jpg") {
placeholder(R.drawable.image)
transformations(CircleCropTransformation())
crossfade(true)
}
imageView.disposeDisplay()
val displayResult = imageView.displayResult
when (displayResult) {
is DisplayResult.Success -> {
val request: DisplayRequest = displayResult.request
val requestKey: String = displayResult.requestKey
val requestCacheKey: String = displayResult.requestCacheKey
val drawable: Drawable = displayResult.drawable
val imageInfo: ImageInfo = displayResult.imageInfo
val dataFrom: DataFrom = displayResult.dataFrom
val transformedList: List<String>? = displayResult.transformedList
val extras: Map<String, String>? = displayResult.extras
// ...
}
is DisplayResult.Error -> {
val request: DisplayRequest = displayResult.request
val drawable: Drawable = displayResult.drawable
val throwable: Throwable = displayResult.throwable
// ...
}
}
Basic functions:
- Get Started
- AnimatedImage: GIF、WEBP、HEIF
- Resize: Modify the image size
- Transformation: Transformation image
- Transition: Display images in cool transitions
- StateImage: Placeholder and error images
- Listener: Listen for request status and download progress
- Cache: Learn about downloads, results, memory caching
- Fetcher: Learn about Fetcher and extend new URI types
- Decoder: Learn about Decoder and expand into new image types
- Target: Apply the load results to the target
- HttpStack: Learn about the HTTP section and using okhttp
- SVG: Decode SVG still images
- VideoFrames: Decode video frames
- Exif: Correct the image orientation
- ImageOptions: Manage image configurations in a unified manner
- RequestInterceptor: Intercept ImageRequest
- DecodeInterceptor: Intercept Bitmap or Drawable decoding
- BitmapPool: Reuse Bitmap to reduce GC
- DownloadRequest: Download the image to disk
- LoadRequest: Load the image to get the Bitmap
- Preload images into memory
- Lifecycle
- Jetpack Compose
- Log
Featured functions:
- SketchImageView: Configure the request through XML attributes
- SketchZoomImageView: Gesture zoom and large image sampling
- Improve the clarity of long images in grid lists
- Displays the download progress
- Displays the image type corner
- Pause image downloads on cellular data to save data
- The list slides to pause the loading of images
- Displays an icon for an apk file or installed app