How to add a watermark to an image in ImageView in Kotlin Android
How to add a watermark to an image in ImageView in Kotlin Android.
Here's a step-by-step tutorial on how to add a watermark to an image in ImageView in Kotlin Android:
Start by creating a new Android project in Android Studio and open the layout file where you want to display the image with the watermark. This layout file should contain an ImageView element.
In your project's
resfolder, create a new folder calleddrawableif it doesn't already exist. Inside thedrawablefolder, add an image file that will serve as your watermark. Make sure the image file has a transparent background and is the desired size and shape for your watermark.Open the Kotlin file associated with your layout file (usually named
MainActivity.kt) and import the necessary classes:import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.DrawableInside the
onCreatemethod of your activity, get a reference to the ImageView element from the layout file:val imageView = findViewById<ImageView>(R.id.imageView)Load the image that you want to display in the ImageView. You can do this using various methods such as using an image URL, loading from the device storage, or using a resource ID. For simplicity, let's assume you're using a resource ID:
imageView.setImageResource(R.drawable.your_image)Create a function to add the watermark to the image. This function should take the original image as a parameter and return a new Bitmap with the watermark added:
fun addWatermarkToImage(originalImage: Bitmap): Bitmap {
val watermark = getDrawable(R.drawable.your_watermark) // Replace with your watermark image resource ID
val bitmap = originalImage.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
watermark.setBounds(0, 0, canvas.width, canvas.height)
watermark.draw(canvas)
return bitmap
}Note: You may need to adjust the position and size of the watermark using the
setBoundsmethod based on your specific requirements.Finally, call the
addWatermarkToImagefunction and set the modified Bitmap as the image resource for the ImageView:val originalBitmap = (imageView.drawable as BitmapDrawable).bitmap
val watermarkedBitmap = addWatermarkToImage(originalBitmap)
imageView.setImageBitmap(watermarkedBitmap)This code assumes that the ImageView already has an image loaded. If the ImageView is empty, you'll need to handle the case when
imageView.drawableis null.
That's it! You have successfully added a watermark to an image in ImageView using Kotlin in Android.