Android ColorMatrix 圖片濾鏡 色調&飽和度&亮度
文章目錄
- 設定三個SeekBar的預設值和最大值並監聽
- SeekBar監聽事件
- 創建新圖片並儲存
- 效果展示
- Github
1.設定三個SeekBar的預設值和最大值並監聽
const val MID_VALUE = 128
private lateinit var seekBarRotate: SeekBar
private lateinit var seekBarSaturation: SeekBar
private lateinit var seekBarScale: SeekBar
//色調SeekBar
seekBarRotate = findViewById(R.id.seekBar_rotate)
seekBarRotate.max = 255
seekBarRotate.progress = MID_VALUE
//飽和度SeekBar
seekBarSaturation = findViewById(R.id.seekBar_saturation)
seekBarSaturation.max = 255
seekBarSaturation.progress = MID_VALUE
//亮度SeekBar
seekBarScale = findViewById(R.id.seekBar_scale)
seekBarScale.max = 255
seekBarScale.progress = MID_VALUE
//SeekBar監聽
seekBarRotate.setOnSeekBarChangeListener(this)
seekBarSaturation.setOnSeekBarChangeListener(this)
seekBarScale.setOnSeekBarChangeListener(this)
2.SeekBar監聽事件
//色調
private val rotateMatrix = ColorMatrix()
//飽和度
private val saturationMatrix = ColorMatrix()
//亮度
private val scaleMatrix = ColorMatrix()
//三合一
private val colorMatrix = ColorMatrix()
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
when (seekBar.id) {
R.id.seekBar_rotate -> {
val mHue = (progress - MID_VALUE).toFloat() / MID_VALUE * 180
rotateMatrix.reset()
rotateMatrix.setRotate(0, mHue)
rotateMatrix.setRotate(1, mHue)
rotateMatrix.setRotate(2, mHue)
}
R.id.seekBar_saturation -> {
val mSaturation = progress / MID_VALUE.toFloat()
saturationMatrix.reset()
saturationMatrix.setSaturation(mSaturation)
}
R.id.seekBar_scale -> {
val mBrightness = progress / MID_VALUE.toFloat()
scaleMatrix.reset()
scaleMatrix.setScale(mBrightness, mBrightness, mBrightness, 1f)
}
}
colorMatrix.reset()
colorMatrix.postConcat(rotateMatrix)
colorMatrix.postConcat(saturationMatrix)
colorMatrix.postConcat(scaleMatrix)
oldImage.colorFilter = ColorMatrixColorFilter(colorMatrix)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
3.創建新圖片並儲存
//原圖
private lateinit var bitmap: Bitmap
//新圖片
private lateinit var newImage: ImageView
fun saveBitmap(view: View) {
bitmap = BitmapFactory.decodeResource(resources, R.drawable.girl)
//新圖放到畫布上
val newBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
//設定畫筆參數(把剛剛設定的三合一參數給畫筆)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.colorFilter = ColorMatrixColorFilter(colorMatrix)
canvas.drawBitmap(bitmap, 0f, 0f, paint)
val file = File(externalCacheDir, "matrixGirl.jpg")
val ops = FileOutputStream(file)
newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ops)
newImage = findViewById(R.id.newImage)
newImage.setImageBitmap(newBitmap)
}
4.效果展示
5.Github
ColorMatrixDemo