Joel Broström
Joel Broström

Reputation: 4090

How do I modify the source variable 'this' in an extension

I'm trying to make an extension for rotating a bitmap, and it seams the only way to do so is to create a new bitmap and rotate it in Bitmap.createBitmap(...).

My problem is I don't want the function to return any value, just modify itself.

Is this doable?

Code so far:

fun Bitmap.adjustToNaturalOrientation(image_absolute_path: String) {
    val exifInterface = ExifInterface(image_absolute_path)
    val orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)

    when (orientation) {

        ExifInterface.ORIENTATION_ROTATE_90 -> rotate( 90f)

        ExifInterface.ORIENTATION_ROTATE_180 -> rotate( 180f)

        ExifInterface.ORIENTATION_ROTATE_270 -> rotate(270f)

        ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> flip(true, false)

        ExifInterface.ORIENTATION_FLIP_VERTICAL -> flip( false, true)
    }

}

fun Bitmap.rotate(degrees: Float): Bitmap {
    val matrix =  Matrix()
    matrix.postRotate(degrees)
    return Bitmap.createBitmap(this, 0, 0, this.width, this.height, matrix, true) // Returns a new bitmap.
}

fun Bitmap.flip(flipHorizontal: Boolean, flipVertical: Boolean) {
    val matrix =  Matrix()
    matrix.preScale(if(flipHorizontal)  -1f else 1f, if(flipVertical) -1f else 1f)
    this = Bitmap.createBitmap(this, 0, 0, this.width, this.height, matrix, true)// Does not compile
}

I want the functionality of flip, with no return value.

In my main activity I just want to write :

mBitmap.adjustToNaturalOrientation(src)

Upvotes: 0

Views: 35

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 82087

You cannot do this and it would not be a good style anyway. You should consider returning a new instance instead:

mBitmap = mBitmap.adjustToNaturalOrientation(src)

fun Bitmap.adjustToNaturalOrientation(image_absolute_path: String): Bitmap

fun Bitmap.flip(flipHorizontal: Boolean, flipVertical: Boolean): BitMap {
    val matrix =  Matrix()
    matrix.preScale(if(flipHorizontal)  -1f else 1f, if(flipVertical) -1f else 1f)
    return Bitmap.createBitmap(this, 0, 0, this.width, this.height, matrix, true)
}

Upvotes: 1

Related Questions