How to prevent onClick method on transparent portion of a PNG-loaded ImageView

前端 未结 3 506
北荒
北荒 2020-12-02 21:23

I am currently developing an Android app that displays multiple images (as ImageView\'s) stacked on top of each other. Here is how the layers are currently con

3条回答
  •  盖世英雄少女心
    2020-12-02 21:59

    Bitmap.createBitmap(v.getDrawingCache() and imageView.setDrawingCacheEnabled(true) are depreciated so you can do this by the following snippet code:

    imageView.setOnTouchListener { v, event ->
                val bmp = convertViewToDrawable(v)
                val color: Int = bmp.getPixel(event.x.toInt(), event.y.toInt())
                if (color == Color.TRANSPARENT)
                    return@setOnTouchListener false
                else {
                    Toast.makeText(baseContext, "image clicked", Toast.LENGTH_SHORT).show()
                    return@setOnTouchListener true
                }
            }
    
    private fun convertViewToDrawable(view: View): Bitmap {
            val b = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight,
                Bitmap.Config.ARGB_8888)
            val c = Canvas(b)
            c.translate((-view.scrollX).toFloat(), (-view.scrollY).toFloat())
            view.draw(c)
            return b
        }
    

提交回复
热议问题