Skip to content

Instantly share code, notes, and snippets.

@gtomek
Last active February 1, 2021 09:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtomek/6519ba92af73532c4b6c0a503cc8f462 to your computer and use it in GitHub Desktop.
Save gtomek/6519ba92af73532c4b6c0a503cc8f462 to your computer and use it in GitHub Desktop.
example of how to rotate sweep gradient in android view
/**
* View showing rotating SweepGradient.
*/
class RotatingGradientView @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var middleX = 0f
private var middleY = 0f
private var gradientMatrix = Matrix()
private var rotationAnimator = ValueAnimator.ofFloat(0f, 1f)
private var gradient: SweepGradient? = null
init {
paint.apply {
style = Paint.Style.STROKE
strokeWidth = resources.getDimension(R.dimen.space_small)
}
rotationAnimator.apply {
addUpdateListener {
gradientMatrix.postRotate(-ROTATION_ANGLE, middleX, middleY)
gradient?.setLocalMatrix(gradientMatrix)
invalidate()
}
duration = ANIMATION_DURATION_MS
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.RESTART
interpolator = LinearInterpolator()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
middleX = w / 2f
middleY = h / 2f
val colorWhite = ContextCompat.getColor(context, R.color.color_light)
val colorDark = ContextCompat.getColor(context, R.color.color_dark)
gradient = SweepGradient(middleX, middleY, colorDark, colorWhite).apply {
setLocalMatrix(gradientMatrix)
}
paint.shader = gradient
rotationAnimator.start()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// draw a shape
val width = measuredWidth
val height = measuredHeight
val strokeWidth = paint.strokeWidth
canvas.drawLine(
0f, height * 0.07f + strokeWidth, width / 2f,
strokeWidth / 2f, paint
)
canvas.drawLine(width / 2f, strokeWidth / 2f, width.toFloat(), height * 0.07f + strokeWidth, paint)
canvas.drawLine(
width - strokeWidth / 2f, height * 0.1f + strokeWidth,
width - strokeWidth / 2f, height * 0.66f - strokeWidth, paint
)
canvas.drawLine(
strokeWidth / 2f, height * 0.1f + strokeWidth, strokeWidth / 2f,
height * 0.66f - strokeWidth, paint
)
canvas.drawLine(
width.toFloat(), height * 0.66f - strokeWidth, width / 2f,
height - strokeWidth, paint
)
canvas.drawLine(
0f, height * 0.66f - strokeWidth, width / 2f,
height - strokeWidth, paint
)
}
override fun onDetachedFromWindow() {
rotationAnimator.cancel()
super.onDetachedFromWindow()
}
companion object {
private const val ROTATION_ANGLE = 5f
private const val ANIMATION_DURATION_MS = 1000L
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment