问题
Background
I wanted (here) to see how to create an alternative to AdaptiveIconDrawable
, but change its background drawable to be shaped in to a given Path
.
The problem
Well, what I did worked for Bitmap, but I wanted to know if it's possible to convert a given Drawable directly to a Bitmap and even a Drawable that is shaped to the given Path
, without creating extra Bitmap instances.
What I've tried
This is the current code :
fun resizePath(path: Path, width: Float, height: Float): Path {
val bounds = RectF(0f, 0f, width, height)
val resizedPath = Path(path)
val src = RectF()
resizedPath.computeBounds(src, true)
val resizeMatrix = Matrix()
resizeMatrix.setRectToRect(src, bounds, Matrix.ScaleToFit.CENTER)
resizedPath.transform(resizeMatrix)
return resizedPath
}
fun getMaskedBitmap(src: Bitmap, path: Path, resizePathToMatchBitmap: Boolean = true): Bitmap {
val pathToUse = if (resizePathToMatchBitmap) resizePath(path, src.width.toFloat(), src.height.toFloat()) else path
val output = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = 0XFF000000.toInt()
canvas.drawPath(pathToUse, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(src, 0f, 0f, paint)
return output
}
fun getMaskedBitmap(drawable: Drawable, path: Path, resizePathToMatchBitmap: Boolean = true): Bitmap = getMaskedBitmap(drawable.toBitmap(), path, resizePathToMatchBitmap)
As you can see, getMaskedBitmap
converts the given drawable to a Bitmap, and inside it creates yet another Bitmap.
The questions
- Is it possible to use only a single Bitmap, which will be the output one?
- Is it possible to have a Drawable as the output, so that it will work even with VectorDrawable, allowing you to scale it nicely ?
来源:https://stackoverflow.com/questions/61541302/given-a-drawable-how-to-mask-it-to-a-given-shape