接口
Transformation.kt
package coil.transform
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Bitmap.Config.RGBA_F16
import android.graphics.drawable.BitmapDrawable
import coil.decode.DecodeResult
import coil.fetch.DrawableResult
import coil.request.ImageRequest
import coil.size.Size
/**
* An interface for making transformations to an image's pixel data.
*
* NOTE: If [DrawableResult.drawable] or [DecodeResult.drawable] is not a [BitmapDrawable],
* it will be converted to one. This will cause animated drawables to only draw the first frame of
* their animation.
*
* @see ImageRequest.Builder.transformations
*/
interface Transformation {
/**
* The unique cache key for this transformation.
*
* The key is added to the image request's memory cache key and should contain any params that
* are part of this transformation (e.g. size, scale, color, radius, etc.).
*/
val cacheKey: String
/**
* Apply the transformation to [input] and return the transformed [Bitmap].
*
* @param input The input [Bitmap] to transform.
* Its config will always be [ARGB_8888] or [RGBA_F16].
* @param size The size of the image request.
* @return The transformed [Bitmap].
*/
suspend fun transform(input: Bitmap, size: Size): Bitmap
}
圆形
CircleCropTransformation.kt
@file:Suppress("unused")
package coil.transform
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import coil.size.Size
import coil.util.safeConfig
import kotlin.math.min
/**
* A [Transformation] that crops an image using a centered circle as the mask.
*
* If you're using Jetpack Compose, use `Modifier.clip(CircleShape)` instead of this transformation
* as it's more efficient.
*/
class CircleCropTransformation : Transformation {
override val cacheKey: String = javaClass.name
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val minSize = min(input.width, input.height)
val radius = minSize / 2f
val output = createBitmap(minSize, minSize, input.safeConfig)
output.applyCanvas {
drawCircle(radius, radius, radius, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
drawBitmap(input, radius - input.width / 2f, radius - input.height / 2f, paint)
}
return output
}
override fun equals(other: Any?) = other is CircleCropTransformation
override fun hashCode() = javaClass.hashCode()
}
圆形
圆角
RoundedCornersTransformation.kt
@file:Suppress("unused")
package coil.transform
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.RectF
import android.graphics.Shader
import androidx.annotation.Px
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import coil.decode.DecodeUtils
import coil.size.Scale
import coil.size.Size
import coil.size.pxOrElse
import coil.util.safeConfig
import kotlin.math.roundToInt
/**
* A [Transformation] that crops the image to fit the target's dimensions and rounds the corners of
* the image.
*
* If you're using Jetpack Compose, use `Modifier.clip(RoundedCornerShape(radius))` instead of this
* transformation as it's more efficient.
*
* @param topLeft The radius for the top left corner.
* @param topRight The radius for the top right corner.
* @param bottomLeft The radius for the bottom left corner.
* @param bottomRight The radius for the bottom right corner.
*/
class RoundedCornersTransformation(
@Px private val topLeft: Float = 0f,
@Px private val topRight: Float = 0f,
@Px private val bottomLeft: Float = 0f,
@Px private val bottomRight: Float = 0f
) : Transformation {
constructor(@Px radius: Float) : this(radius, radius, radius, radius)
init {
require(topLeft >= 0 && topRight >= 0 && bottomLeft >= 0 && bottomRight >= 0) {
"All radii must be >= 0."
}
}
override val cacheKey = "${javaClass.name}-$topLeft,$topRight,$bottomLeft,$bottomRight"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val dstWidth = size.width.pxOrElse { input.width }
val dstHeight = size.height.pxOrElse { input.height }
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = input.width,
srcHeight = input.height,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = Scale.FILL
)
val outputWidth = (dstWidth / multiplier).roundToInt()
val outputHeight = (dstHeight / multiplier).roundToInt()
val output = createBitmap(outputWidth, outputHeight, input.safeConfig)
output.applyCanvas {
drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
val matrix = Matrix()
matrix.setTranslate((outputWidth - input.width) / 2f, (outputHeight - input.height) / 2f)
val shader = BitmapShader(input, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
shader.setLocalMatrix(matrix)
paint.shader = shader
val radii = floatArrayOf(
topLeft, topLeft,
topRight, topRight,
bottomRight, bottomRight,
bottomLeft, bottomLeft
)
val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
val path = Path().apply { addRoundRect(rect, radii, Path.Direction.CW) }
drawPath(path, paint)
}
return output
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is RoundedCornersTransformation &&
topLeft == other.topLeft &&
topRight == other.topRight &&
bottomLeft == other.bottomLeft &&
bottomRight == other.bottomRight
}
override fun hashCode(): Int {
var result = topLeft.hashCode()
result = 31 * result + topRight.hashCode()
result = 31 * result + bottomLeft.hashCode()
result = 31 * result + bottomRight.hashCode()
return result
}
}
圆角
模糊(官方已移除)
BlurTransformation.kt
@file:Suppress("unused")
package coil.transform
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import androidx.annotation.RequiresApi
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import coil.size.Size
import coil.util.safeConfig
/**
* A [Transformation] that applies a Gaussian blur to an image.
*
* @param context The [Context] used to create a [RenderScript] instance.
* @param radius The radius of the blur.
* @param sampling The sampling multiplier used to scale the image. Values > 1
* will downscale the image. Values between 0 and 1 will upscale the image.
*/
@RequiresApi(18)
class BlurTransformation @JvmOverloads constructor(
private val context: Context,
private val radius: Float = DEFAULT_RADIUS,
private val sampling: Float = DEFAULT_SAMPLING
) : Transformation {
init {
require(radius in 0.0..25.0) { "radius must be in [0, 25]." }
require(sampling > 0) { "sampling must be > 0." }
}
override val cacheKey: String = "${BlurTransformation::class.java.name}-$radius-$sampling"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val scaledWidth = (input.width / sampling).toInt()
val scaledHeight = (input.height / sampling).toInt()
val output = createBitmap(scaledWidth, scaledHeight, input.safeConfig)
output.applyCanvas {
scale(1 / sampling, 1 / sampling)
drawBitmap(input, 0f, 0f, paint)
}
var script: RenderScript? = null
var tmpInt: Allocation? = null
var tmpOut: Allocation? = null
var blur: ScriptIntrinsicBlur? = null
try {
script = RenderScript.create(context)
tmpInt = Allocation.createFromBitmap(
script,
output,
Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT
)
tmpOut = Allocation.createTyped(script, tmpInt.type)
blur = ScriptIntrinsicBlur.create(script, Element.U8_4(script))
blur.setRadius(radius)
blur.setInput(tmpInt)
blur.forEach(tmpOut)
tmpOut.copyTo(output)
} finally {
script?.destroy()
tmpInt?.destroy()
tmpOut?.destroy()
blur?.destroy()
}
return output
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is BlurTransformation &&
context == other.context &&
radius == other.radius &&
sampling == other.sampling
}
override fun hashCode(): Int {
var result = context.hashCode()
result = 31 * result + radius.hashCode()
result = 31 * result + sampling.hashCode()
return result
}
override fun toString(): String {
return "BlurTransformation(context=$context, radius=$radius, sampling=$sampling)"
}
private companion object {
private const val DEFAULT_RADIUS = 10f
private const val DEFAULT_SAMPLING = 1f
}
}
模糊
灰度(官方已移除)
BlurTransformation.kt
@file:Suppress("unused")
package coil.transform
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import androidx.annotation.RequiresApi
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import coil.size.Size
import coil.util.safeConfig
/**
* A [Transformation] that applies a Gaussian blur to an image.
*
* @param context The [Context] used to create a [RenderScript] instance.
* @param radius The radius of the blur.
* @param sampling The sampling multiplier used to scale the image. Values > 1
* will downscale the image. Values between 0 and 1 will upscale the image.
*/
@RequiresApi(18)
class BlurTransformation @JvmOverloads constructor(
private val context: Context,
private val radius: Float = DEFAULT_RADIUS,
private val sampling: Float = DEFAULT_SAMPLING
) : Transformation {
init {
require(radius in 0.0..25.0) { "radius must be in [0, 25]." }
require(sampling > 0) { "sampling must be > 0." }
}
override val cacheKey: String = "${BlurTransformation::class.java.name}-$radius-$sampling"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val scaledWidth = (input.width / sampling).toInt()
val scaledHeight = (input.height / sampling).toInt()
val output = createBitmap(scaledWidth, scaledHeight, input.safeConfig)
output.applyCanvas {
scale(1 / sampling, 1 / sampling)
drawBitmap(input, 0f, 0f, paint)
}
var script: RenderScript? = null
var tmpInt: Allocation? = null
var tmpOut: Allocation? = null
var blur: ScriptIntrinsicBlur? = null
try {
script = RenderScript.create(context)
tmpInt = Allocation.createFromBitmap(
script,
output,
Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT
)
tmpOut = Allocation.createTyped(script, tmpInt.type)
blur = ScriptIntrinsicBlur.create(script, Element.U8_4(script))
blur.setRadius(radius)
blur.setInput(tmpInt)
blur.forEach(tmpOut)
tmpOut.copyTo(output)
} finally {
script?.destroy()
tmpInt?.destroy()
tmpOut?.destroy()
blur?.destroy()
}
return output
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is BlurTransformation &&
context == other.context &&
radius == other.radius &&
sampling == other.sampling
}
override fun hashCode(): Int {
var result = context.hashCode()
result = 31 * result + radius.hashCode()
result = 31 * result + sampling.hashCode()
return result
}
override fun toString(): String {
return "BlurTransformation(context=$context, radius=$radius, sampling=$sampling)"
}
private companion object {
private const val DEFAULT_RADIUS = 10f
private const val DEFAULT_SAMPLING = 1f
}
}
灰度
网格(自定义)
注意这里没有考虑 Size 参数,所以最后图片若有裁剪(比如 CENTER_CROP)则图片中显示出来的格子数量可能和设置的数量对不上。若需考虑 Size 参数的影响,参见 圆角
的处理过程。
GridTransformation.kt
package coil.transform
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import coil.size.Size
import coil.util.safeConfig
class GridTransformation(
private val row: Int = 1,
private val column: Int = 1,
private val dividerWidth: Int = 1
) : Transformation {
init {
require(row > 0 && column > 0 && dividerWidth > 0) {
"invalid params: $row, $column, $dividerWidth"
}
}
override val cacheKey: String
get() = "${javaClass.name}-$row,$column,$dividerWidth"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
if (row == 1 && column == 1) {
return input
}
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val output = createBitmap(input.width, input.height, input.safeConfig)
output.applyCanvas {
drawBitmap(input, 0f, 0f, paint)
paint.strokeWidth = dividerWidth.toFloat()
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
val gridHeight = input.height / row.toFloat()
if (gridHeight > 1 && gridHeight - dividerWidth > 1) {
for (i in 1 until row) {
drawLine(
0f,
gridHeight * i,
input.width.toFloat(),
gridHeight * i,
paint
)
}
}
val gridWidth = input.width / column.toFloat()
if (gridWidth > 1 && gridWidth - dividerWidth > 1) {
for (j in 1 until column) {
drawLine(
gridWidth * j,
0f,
gridWidth * j,
input.height.toFloat(),
paint
)
}
}
}
return output
}
}
改进版 GridTransformation
class GridTransformation(
private val row: Int = 1,
private val column: Int = 1,
private val dividerWidth: Int = 1
) : Transformation {
init {
require(row > 0 && column > 0 && dividerWidth > 0) {
"invalid params: $row, $column, $dividerWidth"
}
}
override val cacheKey: String
get() = "${javaClass.name}-$row,$column,$dividerWidth"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
if (row == 1 && column == 1) {
return input
}
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val dstWidth = size.width.pxOrElse { input.width }
val dstHeight = size.height.pxOrElse { input.height }
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = input.width,
srcHeight = input.height,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = Scale.FILL
)
val outputWidth = (dstWidth / multiplier).roundToInt()
val outputHeight = (dstHeight / multiplier).roundToInt()
val output = createBitmap(outputWidth, outputHeight, input.safeConfig)
output.applyCanvas {
drawBitmap(input, 0f, 0f, paint)
paint.strokeWidth = dividerWidth.toFloat()
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
val gridHeight = outputHeight / row.toFloat()
if (gridHeight > 1 && gridHeight - dividerWidth > 1) {
for (i in 1 until row) {
drawLine(
0f,
gridHeight * i,
outputWidth.toFloat(),
gridHeight * i,
paint
)
}
}
val gridWidth = outputWidth / column.toFloat()
if (gridWidth > 1 && gridWidth - dividerWidth > 1) {
for (j in 1 until column) {
drawLine(
gridWidth * j,
0f,
gridWidth * j,
outputHeight.toFloat(),
paint
)
}
}
}
return output
}
}
网格
百叶窗
叠加
几种效果是可以叠加使用的。
圆形+灰度+网格
网友评论