Skip to main content

How to resize an image in ImageView in Kotlin Android

How to resize an image in ImageView in Kotlin Android.

Here's a step-by-step tutorial on how to resize an image in an ImageView in Kotlin for Android:

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Choose an appropriate project name and select the Kotlin language as the default programming language.

Step 2: Add an ImageView to your layout file

Open the activity_main.xml layout file and add an ImageView element. You can do this by dragging and dropping an ImageView from the palette onto the design view of the layout file, or by manually editing the XML code.

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image"
android:scaleType="fitCenter"
/>

In this example, we have set the scaleType attribute to "fitCenter" to ensure that the image is resized to fit the ImageView while maintaining its aspect ratio.

Step 3: Load the image into the ImageView

Next, you need to load the image into the ImageView programmatically. Open the MainActivity.kt file and find the onCreate() method. Inside this method, add the following code:

val imageView: ImageView = findViewById(R.id.imageView)
val drawable: Drawable = resources.getDrawable(R.drawable.image)
imageView.setImageDrawable(drawable)

Here, we first obtain a reference to the ImageView using its ID. Then, we get the Drawable object corresponding to the image resource (in this case, "image") using the resources.getDrawable() method. Finally, we set the drawable as the image source for the ImageView using the setImageDrawable() method.

Step 4: Resize the image programmatically

To resize the image programmatically, you can use the setLayoutParams() method of the ImageView. Add the following code after setting the image drawable in the onCreate() method:

val layoutParams: ViewGroup.LayoutParams = imageView.layoutParams
layoutParams.width = 500 // desired width in pixels
layoutParams.height = 300 // desired height in pixels
imageView.layoutParams = layoutParams

In this example, we set the width and height of the ImageView to 500 and 300 pixels, respectively. You can adjust these values according to your requirements.

Step 5: Run the app

Finally, run the app on an Android emulator or a physical device. The image should now be resized according to the dimensions specified in the code.

That's it! You have successfully resized an image in an ImageView using Kotlin in Android. Experiment with different image sizes and scale types to achieve the desired result.