how to do flip horizontal for ImageView kotlin
import android.content.Context
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.ImageView
class FlippableImageView : ImageView {
private var flippedHorizontally: Boolean = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
init {
scaleType = ScaleType.MATRIX
}
override fun onDraw(canvas: android.graphics.Canvas) {
if (flippedHorizontally) {
val matrix = imageMatrix
matrix.setScale(-1f, 1f, width / 2.toFloat(), height / 2.toFloat())
imageMatrix = matrix
}
super.onDraw(canvas)
}
fun flipHorizontally() {
flippedHorizontally = !flippedHorizontally
invalidate()
}
}
You can use the FlippableImageView
in your XML layout like a regular ImageView
:
<your.package.name.FlippableImageView
android:id="@+id/flippableImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image" />
And then, in your Kotlin code, you can flip the image horizontally by calling the flipHorizontally()
method on the FlippableImageView
instance:
val flippableImageView: FlippableImageView = findViewById(R.id.flippableImageView)
flippableImageView.flipHorizontally()