Android createScaledBitmap与Canvas通过RectF drawBitmap生成马赛克/高斯模糊(毛玻璃)对比,Kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.RectF
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.toRect
class MainActivity : AppCompatActivity() {
private var mScaleFactor = 16f //值越大,马赛克效果越强。
private var mSrcBmp: Bitmap? = null
private val mResId = R.mipmap.pic
private var mSrcBmpW = 0
private var mSrcBmpH = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val image1 = findViewById<ImageView>(R.id.image1)
val image2 = findViewById<ImageView>(R.id.image2)
mSrcBmp = BitmapFactory.decodeResource(resources, mResId, null)
mSrcBmpW = mSrcBmp!!.width
mSrcBmpH = mSrcBmp!!.height
val smallBmp = getSmallBmp(mSrcBmp!!)
image1.setImageBitmap(Bitmap.createScaledBitmap(smallBmp, mSrcBmpW, mSrcBmpH, true))
image2.setImageBitmap(getScaleBmp(smallBmp))
}
private fun getSmallBmp(srcBmp: Bitmap): Bitmap {
return Bitmap.createScaledBitmap(srcBmp, (mSrcBmpW / mScaleFactor).toInt(), (mSrcBmpH / mScaleFactor).toInt(), true)
}
private fun getScaleBmp(srcBmp: Bitmap): Bitmap {
//空Bitmap
val dstBmp = Bitmap.createBitmap(mSrcBmpW, mSrcBmpH, Bitmap.Config.ARGB_8888)
val srcRectF = RectF(0f, 0f, srcBmp.width.toFloat(), srcBmp.height.toFloat())
val dstRectF = RectF(0f, 0f, mSrcBmpW.toFloat(), mSrcBmpH.toFloat())
val c = Canvas(dstBmp)
c.drawBitmap(srcBmp, srcRectF.toRect(), dstRectF.toRect(), null)
return dstBmp
}
}
自上往下,第一张是原图,第二张是通过
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
boolean filter)
先把原图缩小1/n,然后再放大到原图等同大小,实现马赛克,发现这种方式生成的Bitmap,肯定可以达到马赛克效果,并基本接近高斯模糊效果。
第三张图是通过Canvas的
public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst,
@Nullable Paint paint)
基于RectF放大小图到原图大小,发现马赛克的颗粒度更大,更具备马赛克典型特征。
总结起来,
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
boolean filter)
生成的图更平滑。
这种方式生成的图:
public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst,
@Nullable Paint paint)
尤其是放大情况下,拉伸的跨越明显,更具大颗粒度的马赛克效果。