Background
I know that it is possible to create a rotating version of Drawable (or Bitmap) as such (written about it here ):
@JvmStatic
fun getRotateDrawable(d: Drawable, angle: Int): Drawable {
if (angle % 360 == 0)
return d
return object : LayerDrawable(arrayOf(d)) {
override fun draw(canvas: Canvas) {
canvas.save()
canvas.rotate(angle.toFloat(), (d.bounds.width() / 2).toFloat(), (d.bounds.height() / 2).toFloat())
super.draw(canvas)
canvas.restore()
}
}
}
Problem
I wanted it to autoMirrored
be installed on some drawable (VectorDrawable in my case) that would flip over (mirror so that the left one is right and the right one is left, but does not affect the top and bottom) if the locale of the device is RTL.
As an example (and this is just an example!), If you take a drawable that shows a left arrow, after clicking it will be a right arrow.
Unfortunately, this is only available from API 19.
That's why I decided to make it a new Drawable, to be an upside down version of the original
What i tried
, , . :
@JvmStatic
fun getMirroredDrawable(d: Drawable): Drawable {
return object : LayerDrawable(arrayOf(d)) {
override fun draw(canvas: Canvas) {
canvas.save()
val matrix = Matrix()
matrix.preScale(-1.0f, 1.0f);
canvas.matrix = matrix
super.draw(canvas)
canvas.restore()
}
}
}
, - . , , , .
Drawable, , Drawable?
:
( ), :
fun Drawable.getMirroredDrawable(): Drawable {
return object : LayerDrawable(arrayOf(this)) {
val drawingRect = Rect()
val matrix = Matrix()
override fun draw(canvas: Canvas) {
matrix.reset()
matrix.preScale(-1.0f, 1.0f, canvas.width / 2.0f, canvas.height / 2.0f)
canvas.matrix = matrix
drawingRect.left = (canvas.width - intrinsicWidth) / 2
drawingRect.top = (canvas.height - intrinsicHeight) / 2
drawingRect.right = drawingRect.left + intrinsicWidth
drawingRect.bottom = drawingRect.top + intrinsicHeight
if (bounds != drawingRect)
bounds = drawingRect
super.draw(canvas)
}
}
}