0

I have an image with a transparent background. I've put it in the label of a button. I want the button to only be tappable on the non-transparent parts of the image. My understanding is that I can make my button have a clip shape which will limit the tappable area, but my picture has a very odd shape and giving the button a generic "bounding box" so to speak would not be sufficient. It would end up with either far too much tappable space outside the image or far too little of the image being tappable.

So my question is: Can I make the button ONLY tappable on the solid or non-transparent parts of the image?

I've had a few ideas that might work, but I lack the experience to set them up. For example:

  • Make a button, and add modifiers to make the frame of the button equivalent to the image, clipping out any transparent areas
  • Make a custom shape from the image, and set the button's clip shape to that shape
  • Somehow extract the opaque parts of the image, like a mask, and use that for a clip shape or similar
HangarRash
  • 7,314
  • 5
  • 5
  • 32
  • Making a custom shape from a bitmapped mask (or the non-transparent parts) is not a simple task. There is no built-in API to do that, as far as I'm aware. However, you might be able to mask your image with a processed copy of itself. I'm not sure if that affects hit testing though. – hayesk Aug 26 '23 at 20:17
  • I've wrestled with the same situation just a couple of days ago. The "SwiftUI" way of constraining hit testing seems to be the `.contentShape()` modifier, however, it requires a `Shape` and I couldn't find an easy way of making it from a raster image. Ended up creating a custom shape using `Path`. There is a bunch of similar questions, like this one: https://stackoverflow.com/questions/60307286/swiftui-image-pass-through-touches-on-transparent-pixels, the gist seems to be "detect the tap location and look if the image has a transparent pixel there". – Baglan Aug 27 '23 at 04:22

0 Answers0