Android矩阵Matrix在1张宽平大Bitmap批量绘制N个小Bitmap,Kotlin(1)
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "fly"
const val IMG_SIZE = 200
const val IMG_COUNT = 5
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val image5 = findViewById<ImageView>(R.id.image5)
myDrawMultiBitmap(image5)
}
private fun myDrawMultiBitmap(imageView: ImageView) {
imageView.scaleType = ImageView.ScaleType.CENTER_CROP
val options = BitmapFactory.Options()
options.outWidth = IMG_SIZE
options.outHeight = IMG_SIZE
options.inPreferredConfig = Bitmap.Config.RGB_565
val bitmaps = ArrayList<Bitmap>()
for (i in 0 until IMG_COUNT) {
if (i % 2 == 0) {
val b = BitmapFactory.decodeResource(resources, R.mipmap.img, options)
bitmaps.add(b)
} else {
val b = BitmapFactory.decodeResource(resources, R.mipmap.pic, options)
bitmaps.add(b)
}
}
val resultBitmap = Bitmap.createBitmap(IMG_SIZE * IMG_COUNT, IMG_SIZE, Bitmap.Config.RGB_565)
val canvas = Canvas(resultBitmap)
canvas.drawColor(Color.LTGRAY)
bitmaps.forEachIndexed { index, bitmap ->
val w = bitmap.width
val h = bitmap.height
val srcRct = RectF(0f, 0f, w.toFloat(), h.toFloat())
val dstRctLeft = index * IMG_SIZE.toFloat()
val dstRct = RectF(dstRctLeft, 0f, dstRctLeft + IMG_SIZE, IMG_SIZE.toFloat())
val paint = Paint()
if (index % 2 == 0) {
paint.color = Color.RED
} else {
paint.color = Color.BLUE
}
canvas.drawRect(dstRct, paint)
val mx = Matrix()
mx.setRectToRect(srcRct, dstRct, Matrix.ScaleToFit.CENTER)
canvas.drawBitmap(bitmap, mx, null)
}
imageView.setImageBitmap(resultBitmap)
}
}
遗留问题,需要把BitmapFactory解码出来的Bitmap最终以中心缩放格式绘制到大宽平Bitmap上。这里没有实现中心缩放centerCrop。