In this post let’s look at how to do this cool animation using ObjectAnimator.
This is built on top of previous post
class CameraView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val paint = Paint(Paint.ANTI_ALIAS_FLAG) private val imageSize = dp2px(200) private val leftPadding = dp2px(100) private val topPadding = dp2px(100) private val image = getAvatar(imageSize) private val camera = Camera() private var cameraRotationUpper = 0.
Let’s look at how to use camera in canvas transformation.
First this is what we want to implement:
The trick is to draw the upper and lower part separately. And we are using this “reverse drawing” technique.
Upper part override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.save() canvas.drawBitmap(image, leftPadding, topPadding, paint) canvas.restore() }
override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.save() canvas.translate(-(leftPadding + imageSize / 2), -(topPadding + imageSize / 2)) canvas.
In this post I want to go into details on canvas transformations, especially if we want to combine them.
Let’s take the simple example of translation + rotation. The end result is like this:
We can easily see that the image has been translated to (300, 200) and then rotated 45 degrees.
class TransformView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val paint = Paint(Paint.
Let’s use Xfermode to draw a circled avatar.
The original avatar image is this:
We will implement a custom view that clips it into a circle.
class Avatar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val WIDTH = dp2px(300) private val PADDING = dp2px(50) val paint = Paint(Paint.ANTI_ALIAS_FLAG) val bitmap = getAvatar(WIDTH.toInt()) val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) val savedArea = RectF() override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.
In this tutorial let’s see how to draw a piechart.
class PieChart @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) val bounds: RectF = RectF() val RADIUS = dp2px(150) val OFFSET = dp2px(50) var offsetIndex = 2 val angles = arrayOf(60.0f, 120.0f, 30.0f, 150.0f) val colors = arrayOf("#07004d", "#2d82b7", "#42e2b8", "#f3dfbf") override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.