Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
Created April 15, 2018 09:36
Show Gist options
  • Select an option

  • Save EmmanuelGuther/006d60dd29b5bc1444951ae2344df542 to your computer and use it in GitHub Desktop.

Select an option

Save EmmanuelGuther/006d60dd29b5bc1444951ae2344df542 to your computer and use it in GitHub Desktop.
Kotlin circular imageview
class CircularImageView : ImageView {
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}
override fun onDraw(canvas: Canvas) {
val drawable = drawable ?: return
if (width == 0 || height == 0) {
return
}
val b = (drawable as BitmapDrawable).bitmap
val bitmap = b.copy(Config.ARGB_8888, true)
val w = width
val roundBitmap = getCroppedBitmap(bitmap, w)
canvas.drawBitmap(roundBitmap, 0f, 0f, null)
}
companion object {
fun getCroppedBitmap(bmp: Bitmap, radius: Int): Bitmap {
val sbmp: Bitmap
sbmp = if (bmp.width != radius || bmp.height != radius) {
val smallest = Math.min(bmp.width, bmp.height).toFloat()
val factor = smallest / radius
Bitmap.createScaledBitmap(bmp, (bmp.width / factor).toInt(), (bmp.height / factor).toInt(), false)
} else {
bmp
}
val output = Bitmap.createBitmap(radius, radius,
Config.ARGB_8888)
val canvas = Canvas(output)
val paint = Paint()
val rect = Rect(0, 0, radius, radius)
paint.isAntiAlias = true
paint.isFilterBitmap = true
paint.isDither = true
canvas.drawARGB(0, 0, 0, 0)
paint.color = Color.parseColor("#BAB399")
canvas.drawCircle(radius / 2 + 0.7f,
radius / 2 + 0.7f, radius / 2 + 0.1f, paint)
paint.xfermode = PorterDuffXfermode(Mode.SRC_IN)
canvas.drawBitmap(sbmp, rect, rect, paint)
return output
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment