Last active
July 16, 2024 22:25
-
-
Save David-Hackro/a132014d4727c00775fad1ec289ee921 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//CircularImageView | |
//-------------------------------------------------------------------------------- | |
import android.content.Context | |
import android.graphics.* | |
import android.graphics.drawable.Drawable | |
import android.util.AttributeSet | |
import android.util.TypedValue | |
import android.view.View | |
class CircularImageView(context: Context, attrs: AttributeSet) : View(context, attrs) { | |
private var drawable: Drawable? = null | |
private val paint = Paint().apply { | |
isAntiAlias = true | |
} | |
private val padding: Float | |
init { | |
// Convert 8dp to pixels | |
padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8f, resources.displayMetrics) | |
} | |
fun setImageDrawable(drawable: Drawable) { | |
this.drawable = drawable | |
invalidate() | |
} | |
override fun onDraw(canvas: Canvas) { | |
super.onDraw(canvas) | |
drawable?.let { | |
val bitmap = getBitmapFromDrawable(it) | |
val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) | |
val matrix = Matrix() | |
// Always use ScaleType.FIT_XY | |
val scaleX = (width - 2 * padding) / bitmap.width.toFloat() | |
val scaleY = (height - 2 * padding) / bitmap.height.toFloat() | |
matrix.setScale(scaleX, scaleY) | |
shader.setLocalMatrix(matrix) | |
paint.shader = shader | |
val radius = (Math.min(width, height) - 2 * padding) / 2f | |
canvas.drawCircle(width / 2f, height / 2f, radius, paint) | |
} | |
} | |
private fun getBitmapFromDrawable(drawable: Drawable): Bitmap { | |
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) | |
val canvas = Canvas(bitmap) | |
drawable.setBounds(0, 0, canvas.width, canvas.height) | |
drawable.draw(canvas) | |
return bitmap | |
} | |
} | |
//-------------------------------------------------------------------------------- | |
//Implamentation | |
val circularImageView = findViewById<CircularImageView>(R.id.circularImageView) | |
val drawable = getDrawable(R.drawable.ic_launcher_background) | |
drawable?.let { | |
circularImageView.setImageDrawable(it) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment