how to make transparent area as untouchable for Im

2019-08-10 09:47发布

问题:

I googled a lot but could not find anything useful. I have a complex png image and I want to make it touchable but for its opaque area only. I set a touch listener for it but it dispatched even I clicked on a transparent area, thats what I DON'T want.

回答1:

As @Cata says, a touch event will be associated with the whole of the image. However, the touch event will tell you where in the image the touch was, and so can code something like this (ignoring checking for correct action etc):

@Override
public boolean onTouchEvent(MotionEvent event) {
    boolean eventHandled = false;

    int x = (int) (event.getX());
    int y = (int) (event.getY());
            if (imageIsOpaque(x,y) {
                 //Do the stuff

                 eventHandled = true;
            }

    return eventHandled;
}

The key here is then imageIsOpaque, which you will need to implement, in one of three ways:

  1. The image may be easy to segment into areas of opaque and non opaque in which case:

    boolean imageIsOpaque(int touchX, int touchY) {
        ArayList<Rect> rectsOfOpaqueness; // You will need to define these ...
    
        boolean isOpaque = false;
        for (int i=0; i<rectsOfOpaqueness.size() && !isOpaque; i++) {
        if (rectsOfOpaqueness.get(i).contains(touchX, touchY)) {
            isOpaque = true;
            }
    
        return isOpaque;
    }
    
  2. The image may not be easy to handle that way, in which case you will need to use the x and y touch position to check in the source image (scaled to the size it's on the screen) whether the point is opaque or not. EDIT: You seem to have used this solution in a rather neat way in your comment to @vinod below, so I would recommend to other readers to check that comment out as well.

  3. Even more complex, it may be an image that you are contructing on the fly and never really know it's final state in a searchable way. If this is the case, you will need to build up a separate 2D array of booleans as you create the image determining which points are opaque and which aren't.



回答2:

Touch listener applies for the entire view and not to a portion of the view.. so I would recommend you to split your image into small pieces and add touch listener on each piece that is opaque.. I hope that can help you, to get more help you can also try to post the image here so we can see better what you want to achieve..



回答3:

@user1716538: Why dont u use png image? U can remove the unwanted part of the image using png image and hence the click event will not occur on those part of the image.