android studio picasso circle image
Open your Android Studio project.
Ensure that you have the necessary dependencies in your app-level build.gradle file:
kotlin implementation 'com.squareup.picasso:picasso:2.71828'
Sync your project to ensure that the new dependency is added.
In your XML layout file, add an ImageView where you want to display the circular image:
xml <ImageView android:id="@+id/circularImageView" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/placeholder_image" android:scaleType="centerCrop"/>
In your Kotlin activity or fragment file, reference the ImageView and load the image using Picasso: ```kotlin import com.squareup.picasso.Picasso
class YourActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.your_layout)
val circularImageView: ImageView = findViewById(R.id.circularImageView)
val imageUrl = "your_image_url_here"
Picasso.get()
.load(imageUrl)
.transform(CircleTransform()) // Custom transformation for circular image
.placeholder(R.drawable.placeholder_image) // Placeholder image while loading
.error(R.drawable.error_image) // Image to display in case of an error
.into(circularImageView)
}
} ```
- Create a custom transformation class for the circular image (CircleTransform.kt): ```kotlin import android.graphics.Bitmap import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Paint import com.squareup.picasso.Transformation
class CircleTransform : Transformation { override fun transform(source: Bitmap): Bitmap { val size = Math.min(source.width, source.height) val x = (source.width - size) / 2 val y = (source.height - size) / 2
val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squaredBitmap != source) {
source.recycle()
}
val bitmap = Bitmap.createBitmap(size, size, source.config)
val canvas = Canvas(bitmap)
val paint = Paint()
val shader = BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val radius = size / 2f
canvas.drawCircle(radius, radius, radius, paint)
squaredBitmap.recycle()
return bitmap
}
override fun key(): String {
return "circle"
}
} ```
- Run your application to see the circular image loaded using Picasso.
Make sure to replace "your_image_url_here," "your_layout," "placeholder_image," and "error_image" with your actual image URL, layout, placeholder image resource, and error image resource, respectively.