How to crop a circular area from bitmap in Android using Kotlin?


This example demonstrates how to crop a circular area from bitmap in Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project, and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#edf2ea"
   android:padding="8dp"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/iv"
      android:layout_width="match_parent"
      android:layout_height="500dp"
      android:layout_centerInParent="true" />
   <Button
      android:id="@+id/btn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:layout_alignParentBottom="true"
      android:text="Crop It" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.graphics.*
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.min
class MainActivity : AppCompatActivity() {
   lateinit var button: Button
   lateinit var imageView: ImageView
   lateinit var bitmap: Bitmap
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      imageView = findViewById(R.id.iv)
      button = findViewById(R.id.btn)
      // Get the bitmap resource id
      // Get the bitmap resource id
      val bitmapResourceID: Int = R.drawable.image
      // Set an image to ImageView
      // Set an image to ImageView
      imageView.setImageBitmap(BitmapFactory.decodeResource(resources, bitmapResourceID))
      // Set a click listener for Button widget
      // Set a click listener for Button widget
      button.setOnClickListener {
         bitmap = BitmapFactory.decodeResource(resources, bitmapResourceID)
         // Create a circular bitmap
         bitmap = getCircularBitmap(bitmap)
         imageView.setImageBitmap(bitmap)
      }
   }
   private fun getCircularBitmap(srcBitmap: Bitmap?): Bitmap {
      val squareBitmapWidth = min(srcBitmap!!.width, srcBitmap.height)
      // Initialize a new instance of Bitmap
      // Initialize a new instance of Bitmap
      val dstBitmap = Bitmap.createBitmap(
         squareBitmapWidth,  // Width
         squareBitmapWidth,  // Height
         Bitmap.Config.ARGB_8888 // Config
      )
      val canvas = Canvas(dstBitmap)
      // Initialize a new Paint instance
      // Initialize a new Paint instance
      val paint = Paint()
      paint.isAntiAlias = true
      val rect = Rect(0, 0, squareBitmapWidth, squareBitmapWidth)
      val rectF = RectF(rect)
      canvas.drawOval(rectF, paint)
      paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
      // Calculate the left and top of copied bitmap
      // Calculate the left and top of copied bitmap
      val left = ((squareBitmapWidth - srcBitmap.width) / 2).toFloat()
      val top = ((squareBitmapWidth - srcBitmap.height) / 2).toFloat()
      canvas.drawBitmap(srcBitmap, left, top, paint)
      // Free the native object associated with this bitmap.
      // Free the native object associated with this bitmap.
      srcBitmap.recycle()
      // Return the circular bitmap
      // Return the circular bitmap
      return dstBitmap
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon Play from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

Click here to download the project code.

Updated on: 28-Nov-2020

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements