Skip to main content

android kotlin - ImageView set image programmatically

Set ImageView Image Programmatically
ImageView is a widget of Android native SDK. ImageView is a very popular element for android app developers. ImageView displays image resources in the android app user interface. ImageView displays images from various sources such as drawable resources and assets resources.An Imageview can display various types of image resources, for example, bitmap and drawable resources.

ImageView also tints an image object and displays the result on its surface. ImageView widget also can scale an image resource. ImageView allows us to apply many types of scaling algorithms.

This android app development tutorial demonstrates how we can set an image to ImageView programmatically. Programmatically setting an image to ImageView means we have to add an image to ImageView by using a kotlin or java file.

To do this, at first we have to create an XML layout file and we will put an ImageView widget on it by using the Imageview tag and available attributes. Next, inside the java or kotlin file, we will use ImageView various methods to add an image to the ImageView widget.

Imageview setImageDrawable() method allows us to add a drawable resource to ImageView that acts as an image. ImageView setImageResource() method can help us to display an image on ImageView from the resource directory. ImageView setImageBitmap() method can directly display a bitmap image to ImageView widget.

This android app development tutorial also demonstrates how can we show an image to ImageView from an URL. We can also get an image object from the assets folder and display it on the ImageView surface. Even we can draw an image object and display it to the ImageView widget.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.*
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.coroutines.*
import java.io.IOException
import java.net.URL
import kotlin.math.min


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the widgets reference from XML layout
        val ivBitmap = findViewById<ImageView>(R.id.ivBitmap)
        val ivDrawable = findViewById<ImageView>(R.id.ivDrawable)
        val ivResource = findViewById<ImageView>(R.id.ivResource)
        val ivAssets = findViewById<ImageView>(R.id.ivAssets)
        val ivUrl = findViewById<ImageView>(R.id.ivUrl)


        // Create a new bitmap and display it on image view
        ivBitmap.setImageBitmap(
            drawCircle(
                color = Color.parseColor("#C5B358"),
                radius = 300f,
                canvasBackground = Color.parseColor("#C80815")
            )
        )


        // Display an image on image view from drawable
        ivDrawable.setImageDrawable(
            ContextCompat.getDrawable(
                applicationContext, // Context
                R.drawable.gradient_rectangle // Drawable
            )
        )


        // Display an image on image view from resource
        ivResource.setImageResource(R.drawable.flower)


        // Display an image into image view from assets folder
        val assetsBitmap: Bitmap? = getBitmapFromAssets("flower100.jpg")
        ivAssets.setImageBitmap(assetsBitmap)


        // Display an image to image view from url
        val url = URL("https://images.pexels.com/photos/954126/" +
                "pexels-photo-954126.jpeg?auto=compress&cs=" +
                "tinysrgb&dpr=2&h=750&w=1260")
        urlToImageView(ivUrl,url)
    }


    // Custom method to get assets folder image as bitmap
    private fun getBitmapFromAssets(fileName: String): Bitmap? {
        return try {
            BitmapFactory.decodeStream(assets.open(fileName))
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }


    // Method to draw a circle on a canvas and generate bitmap
    private fun drawCircle(
        color:Int = Color.LTGRAY,
        bitmapWidth:Int = 1500,
        bitmapHeight:Int = 750,
        radius:Float = min(bitmapWidth, bitmapHeight) / 2f,
        cx:Float = bitmapWidth / 2f,
        cy:Float = bitmapHeight / 2f,
        canvasBackground:Int = Color.WHITE
    ):Bitmap{
        val bitmap = Bitmap.createBitmap(
            bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888
        )

        // Canvas to draw circle
        val canvas = Canvas(bitmap).apply {
            drawColor(canvasBackground)
        }

        // Paint to draw on canvas
        val paint = Paint().apply {
            this.color = color
            isAntiAlias = true
        }

        // Draw circle on canvas
        canvas.drawCircle(
            cx, // X-coordinate of the center of the circle
            cy, // Y-coordinate of the center of the circle
            radius, // Radius of the circle
            paint // Paint used to draw the circle
        )

        return bitmap
    }


    // Method to show image on mage view from an url
    private fun urlToImageView(imageView:ImageView,urlImage:URL){
        // Async task to get bitmap from url
        val result: Deferred<Bitmap?> = GlobalScope.async {
            try {
                BitmapFactory.decodeStream(urlImage.openStream())
            }catch (e:IOException){
                null
            }
        }

        GlobalScope.launch(Dispatchers.Main) {
            // Show bitmap on image view when available
            imageView.setImageBitmap(result.await())
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#DCDCDC">

    <ImageView
        android:id="@+id/ivBitmap"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <ImageView
        android:id="@+id/ivDrawable"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ivBitmap"/>

    <ImageView
        android:id="@+id/ivResource"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ivDrawable"/>

    <ImageView
        android:id="@+id/ivAssets"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ivResource"/>

    <ImageView
        android:id="@+id/ivUrl"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ivAssets"/>

</androidx.constraintlayout.widget.ConstraintLayout>
res/drawable/gradient_rectangle.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#ff6d6d"
                android:centerColor="#69d14d"
                android:endColor="#ffe02e"
                android:angle="45"
                />
            <corners android:radius="10dp"/>
        </shape>
    </item>
</selector>
build.gradle [app] [dependencies]

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...