2018-12-13 imageview 通过maxtrix实现其他ScalType变换

private fun updateBaseMatrix(): Matrix? {

    val drawable = drawable ?: return null
    val viewWidth = (width - paddingLeft - paddingRight).toFloat() //view的宽度
    val viewHeight = (height - paddingTop - paddingBottom).toFloat()
    val drawableWidth = drawable.intrinsicWidth //图片的宽度
    val drawableHeight = drawable.intrinsicHeight

    mBaseMatrix.reset()

    val widthScale = viewWidth / drawableWidth //缩放比例
    val heightScale = viewHeight / drawableHeight //缩放比例

    if (mScaleType == ImageView.ScaleType.CENTER) {
        mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2f,
                (viewHeight - drawableHeight) / 2f)

    } else if (mScaleType == ImageView.ScaleType.CENTER_CROP) {
        val scale = Math.max(widthScale, heightScale)
        mBaseMatrix.postScale(scale, scale)
        mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2f,
                (viewHeight - drawableHeight * scale) / 2f)

    } else if (mScaleType == ImageView.ScaleType.CENTER_INSIDE) {
        val scale = Math.min(1.0f, Math.min(widthScale, heightScale))
        mBaseMatrix.postScale(scale, scale)
        mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2f,
                (viewHeight - drawableHeight * scale) / 2f)

    } else {
        val mTempSrc = RectF(0f, 0f, drawableWidth.toFloat(), drawableHeight.toFloat())
        val mTempDst = RectF(0f, 0f, viewWidth, viewHeight)

        when (mScaleType) {
            ImageView.ScaleType.FIT_CENTER -> mBaseMatrix.setRectToRect(mTempSrc, mTempDst, Matrix.ScaleToFit.CENTER)

            ImageView.ScaleType.FIT_START -> mBaseMatrix.setRectToRect(mTempSrc, mTempDst, Matrix.ScaleToFit.START)

            ImageView.ScaleType.FIT_END -> mBaseMatrix.setRectToRect(mTempSrc, mTempDst, Matrix.ScaleToFit.END)

            ImageView.ScaleType.FIT_XY -> mBaseMatrix.setRectToRect(mTempSrc, mTempDst, Matrix.ScaleToFit.FILL)

            else -> {
            }
        }
    }

    return mBaseMatrix
}

使用:

val matrix = updateBaseMatrix()
imageMatrix = matrix (相当于java的setImageMatrix)

推荐阅读更多精彩内容