ImageView

For Android View, ImageView is used to display images. For Compose, we use Image to display images.

Image(painter = painterResource(id = r.rawable.ic_launcher_background), contentDescription = "This is an Image")Copy the code

The painterResource method is used to pass in the image Id resource and add the text description.

Take a look at the Image source code to learn more about its use:

@composable fun Image(// construct 1 bitmap: ImageBitmap, contentDescription: String? , // Picture description Text modifier: modifier = modifier, // modifier alignment: alignment = align.center, // Align parameters contentScale: ContentScale = contentScale.fit, // Zoom alpha: Float = DefaultAlpha, // transparency colorFilter: colorFilter? = null // color filter) {// omit... } @composable fun Image(Composable fun Image, contentDescription: String? , modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null) {// omit... }Copy the code

These two overloaded methods have the same parameters except for the first parameter. Let’s focus on the type of the first parameter.

ImageBitmap

The bitmap parameter type is ImageBitmap, which is composed’s unique class. The bitmap extension method asImageBitmap can be used to convert the bitmap to the ImageBitmap required by the Image.

Val bitMap = bitmapfactory.decodefile (" imageBitMap = bitmap.asImageBitmap(), contentDescription = "this is a picture ")Copy the code
Painter

The painter argument type is Painter, which is an abstract class with three subclasses, the most commonly used being BitmapPainter.

Because using BitmapPainter directly is a bit complicated, Compose encapsulates the method for us to generate Painter. The painterResource called in the example above is the official recommended method. We just need to pass in the resource Id.

Set image Styles

The Image control has several parameters that are not used, so let’s see what effect each has.

  1. alignment

Alignment is an optional alignment parameter of type alignment, used to place an Image within a range that is customized by width and height.

Image(painter = painterResource(id = r.rawable. Ic_launcher_background), contentDescription = "This is an Image ", alignment = Alignment.Center )Copy the code

Alignments are used to define the Alignment of the parent layout’s sublayouts, which we will learn about later.

  1. contentScale

Used to set horizontal and vertical scaling. Type ContentScale. If the layout boundary size is different from the Image fixed size, you can select the scale parameter to determine the scale scale to use. The default zoom is contentScale.fit, keeping the aspect ratio of the original image. Of course, there are several other types:

*/ Fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor /** * companion object */ Companion Object {/** ** Keep the image aspect ratio so that the width and height of the image are equal to or greater than the corresponding Size of the target. */ @Stable val Crop = object : ContentScale { override fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor = computeFillMaxDimension(srcSize, dstSize). Let {ScaleFactor(it, it)}} So that the width and height of the image are equal to or less than the corresponding size of the target. */ @Stable val Fit = object : ContentScale { override fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor = computeFillMinDimension(srcSize, dstSize). Let {ScaleFactor(it, it)}} /** * Scale the image and keep the aspect ratio so that the boundary matches the target height, Override Fun computeScaleFactor(srcSize: override Fun computeScaleFactor(srcSize: override Fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor = computeFillHeight(srcSize, dstSize).let {ScaleFactor(it, it)}} /** * Scale the image and keep the aspect ratio so that the border matches the target width, if the width is greater than the height, */ @stable Val FillWidth = object: ContentScale {Override Fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor = computeFillWidth(srcSize, dstSize). Let {ScaleFactor(it, it)}} The zooming image keeps the aspect ratio within the target range * If the source content is less than or equal to the target in both width and height dimensions, it behaves like "none". * This will always be included in the target range. */ @Stable val Inside = object : ContentScale { override fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor {return if (srcsie.width <= dstsie.width && srcsie.height <= dstsie.height) {ScaleFactor(1.0f, 1.0f)} else {computeFillMinDimension(srcSize, dstSize).let {ScaleFactor(it, It)}}}} /** * Does not scale the image at all */ @stable Val None = FixedScale(1.0f) /** * Uneven horizontal and vertical scaling to fill the target range */ @stable val FillBounds = object : ContentScale { override fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor = ScaleFactor( computeFillWidth(srcSize, dstSize), computeFillHeight(srcSize, dstSize) ) } } }Copy the code

The above scaling methods can be used according to specific project requirements.

alpha

Image transparency, type Float, alpha in Image DefaultAlpha by default.

Const val DefaultAlpha: Float = 1.0fCopy the code

Constant value is 1.0F and the image is completely opaque. If set to full transparency, set the alpha value to 0F:

Box {Text(Text = "this is a Text ") Image(painter = painterResource(id = r.rawable.ic_launcher_background), Size (200.dp, 200.dp), contentDescription = "this is a picture ", alignment = align.center, alpha = 0.1f)}Copy the code

Here, we use Box, which is equivalent to Framelayout Framelayout in Android View. It is a Text, and an Image is placed on it. After setting the transparency of the picture to 0.1f, the Text under the picture can be clearly seen.

colorFilter

ColorFilter can be used to color an Image, set the color matrix for the Image, and create a simple lighting effect for the Image.

@Immutable class ColorFilter internal constructor(internal val nativeColorFilter: NativeColorFilter) {companion Object { */ Stable fun tint(color: color, blendMode: blendMode = blendmode.srcin): ColorFilter = actualTintColorFilter(color, blendMode) /** * Create a ColorFilter to convert the color through the 4*5 color matrix * This filter can be used to change the saturation of the pixel, */ @stable fun colorMatrix(colorMatrix: colorMatrix): ColorFilter = actualColorMatrixColorFilter (colorMatrix) / * * * create can be used to simulate simple lighting effect ColorFilter * ColorFilter defined by two parameters, Multiply: Color, add: Color, multiply: Color, multiply: Color, multiply: Color, add: Color ColorFilter = actualLightingColorFilter(multiply, add) } }Copy the code

Let’s simply set ColorFilter:

Box {Text(Text = "this is a Text ") Image(painter = painterResource(id = r.rawable.ic_launcher_background), Size (200.dp, 200.dp), contentDescription = "this is a picture ", alignment = align.center, alpha = 1.0f, colorFilter = ColorFilter.tint(Color.Red) ) }Copy the code

Display network diagram

To display a web image in Android, you need to write your own web request, request the downloaded Bitmap to display it through ImageView, Glide, Fresco and so on. It’s not hard to display the network graph in Compose, just add a dependency library:

Implementation 'com. Google. Accompanist: accompanist - coil: 0.10.0'Copy the code

Coil is a new image-loading library, developed by Kotlin, which uses Kotlin’s coroutine. The default network request is Okhttp. Specific use is as follows:

Box {
    Image(
        painter = rememberCoilPainter(request = "https://picsum.photos/300/300"),
        contentDescription = null
    )
}
Copy the code

Let’s look at the rememberCoilPainter construction parameters:

@Composable fun rememberCoilPainter( request: Any? // imageLoader: ImageLoader = CoilPainterDefaults.defaultImageLoader(), / / request ImageLoader used in image, the default for CoilPainterDefaults. DefaultImageLoader shouldRefetchOnSizeChange () : ShouldRefetchOnSizeChange ShouldRefetchOnSizeChange = {} _, _ - > false, / / change the callback, size allows optionally get photo again, Return true to retrieve the image requestBuilder: (Imagerequest.builder.(size: IntSize) -> ImageRequest.Builder)? = null, // ImageRequest optional generator fadeIn: Boolean = false, // Whether to fadeInDurationMs: Int = LoadPainterDefaults FadeInTransitionDuration, / / fade in the animation time (in milliseconds) @ DrawableRes previewPlaceholder: Int = 0, / / to take photo)Copy the code

Other usage of the image to load library can refer to its website: Google. Making. IO/accompanist…

progressBar

The progress bar can be used in many scenarios, such as loading a page, downloading a file, and playing a video.

Circular progress bar

Let’s see how the circular progress bar is used in Compose:

Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, VerticalAlignment = Alignment. CenterVertically) {CircularProgressIndicator () / / circular progress bar}Copy the code

The Row is a horizontal layout, CircularProgressIndicator is circular progress bar, one line of code is done. This real-time refresh control can be awkward to Preview, so it is recommended to run it on a real machine or emulator. Let’s see CircularProgressIndicator source code:

@ Composable fun CircularProgressIndicator (modifier: modifier = modifier, / / modifier color: Color = MaterialTheme. Colors. Primary, / / progress bar Color strokeWidth: Dp = ProgressIndicatorDefaults. StrokeWidth) {/ / / / progress bar width omit... }Copy the code

Let’s look at the use of attributes:

Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, VerticalAlignment = Alignment. CenterVertically) {CircularProgressIndicator (/ / circular progress bar modifier = modifier. The size (80. Dp), color = Color.Red, strokeWidth = 10.dp ) }Copy the code

There is another constructor that sets the progress value:

@ Composable fun CircularProgressIndicator (/ * @ FloatRange (= 0.0, the from to = 1.0) * / progress: Float, modifier: Modifier = Modifier, color: Color = MaterialTheme.colors.primary, strokeWidth: Dp = ProgressIndicatorDefaults.StrokeWidth )Copy the code

The progress parameter is set to 0.0 with no progress and 1.0 with progress completed. It is important to note that the progress bar setting the progress value does not have the animation effect of turning around.

Bar progress bar

The use of bar and circular progress bars is basically the same, let’s take a look:

Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, VerticalAlignment = Alignment. CenterVertically) {LinearProgressIndicator () / / bar bar}Copy the code

Take a look at the source code:

@Composable
fun LinearProgressIndicator(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colors.primary,
    backgroundColor: Color = color.copy(alpha = IndicatorBackgroundOpacity)
)
Copy the code

In addition to modifiers, you can also set the background color:

Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { LinearProgressIndicator( color = Color.Red, // progress bar Color backgroundColor = color.yellow // backgroundColor)}Copy the code

Similarly, you can set progress

@composable Fun LinearProgressIndicator(/* @floatRange (from = 0.0, to = 1.0)*/ Progress: Float, modifier: Modifier = Modifier, color: Color = MaterialTheme.colors.primary, backgroundColor: Color = color.copy(alpha = IndicatorBackgroundOpacity) )Copy the code

After setting the progress, the progress bar also becomes static without animation. We’ll learn about the layout component in Compose later.