Advertisement
Guest User

Untitled

a guest
Nov 11th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.48 KB | None | 0 0
  1. package com.sudox.design.circleImageView
  2.  
  3. import android.content.Context
  4. import android.graphics.*
  5. import android.util.AttributeSet
  6. import kotlin.math.min
  7.  
  8. class CircleImageView : androidx.appcompat.widget.AppCompatImageView {
  9.     private val emptyPaint = Paint()
  10.     private val circlePoint = Paint().apply {
  11.         color = Color.TRANSPARENT
  12.         xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
  13.         isAntiAlias = true
  14.     }
  15.     private val fromBToAPaint = Paint().apply {
  16.         xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
  17.     }
  18.  
  19.     constructor(context: Context) : this(context, null)
  20.     constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
  21.     constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
  22.  
  23.     override fun onDraw(canvas: Canvas?) {
  24.         canvas ?: return
  25.  
  26.         // Create a new layer and draw the image
  27.         val a = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), emptyPaint)
  28.         super.onDraw(canvas)
  29.  
  30.         // Create a new layer to crop a layer
  31.         val b = canvas.saveLayer(0f,0f, width.toFloat(), height.toFloat(), fromBToAPaint)
  32.  
  33.         // Fill and cut circle
  34.         canvas.drawColor(Color.GREEN)
  35.         canvas.drawCircle(width / 2f, height / 2f, min(width, height) / 2f, circlePoint)
  36.  
  37.         // Delete from a the b layer
  38.         canvas.restoreToCount(b)
  39.  
  40.         // Paint result
  41.         canvas.restoreToCount(a)
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement