【问题标题】:How do I modify the source variable 'this' in an extension如何在扩展中修改源变量“this”
【发布时间】:2018-07-06 09:34:57
【问题描述】:

我正在尝试为旋转位图做一个扩展,它接缝的唯一方法是创建一个新位图并在 Bitmap.createBitmap(...) 中旋转它。

我的问题是我不希望函数返回任何值,只需修改自身即可。

这可行吗?

到目前为止的代码:

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
}

我想要翻转的功能,没有返回值。

在我的主要活动中,我只想写:

mBitmap.adjustToNaturalOrientation(src)

【问题讨论】:

    标签: android bitmap kotlin this extension-methods


    【解决方案1】:

    你不能这样做,而且无论如何这都不是一个好的风格。您应该考虑返回一个新实例:

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多