Given a Drawable, how to mask it to a given shape?

人盡茶涼 提交于 2021-01-29 16:20:54

问题


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

  1. Is it possible to use only a single Bitmap, which will be the output one?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!