clickable area of image
Asked Answered
H

5

31

i'am designing a GUI remote control, but instead of making separate buttons for each remote button, i want to get a full ready remote image and set certain parts of it click-able. is there a way rather than the motion event to do this?

Helve answered 21/5, 2013 at 13:5 Comment(7)
You want to make it all in one image?Medellin
is their a way to somehow split an image to rows and columns?Helve
@OutflorksUsus: would you mind if whole image stays clickable but you can surely get precise information of which area has been clicked?Hoffman
@MehulJoisar if this doesn't make false actions when the application runs then no problemHelve
i thought of using gridview layout but i couldn't set a back ground image for itHelve
@OutflorksUsus:ok,let me write an answer for your requirement.Hoffman
I think you should use motion event for this.Indefensible
H
43

I have 2 solutions for your requirement.in both,the whole image stays clickable but you can get information about clicked area.

Solution 1:

you can mask the image and get the pixel color of that underneath image.so ultimately you can come to know which area has been clicked.

here,whenever clicked occurs,you can check the pixel color of background image and match it with predefined color set to know about which area has been clicked.

Foreground image: Foreground image

Background image: Background image

Clickable area: Representing clickable area

Still confused?

Reference: I would like to suggest you to go through this tutorial.

Solution 2:

you can map your image with co-ordinates and accordingly you can get the information of area which has been clicked.

Example: MappedImage with co-ordinates

if you are not aware of co-ordinates,you can create your mappedimage from here

co-ordinates for Kansas will look something like this,

        <area shape="poly" coords="243,162,318,162,325,172,325,196,244,196" id="@+id/area14" name = "Kansas"/>

MappedImage with co-ordinates

Reference: Please have a look at Android Image Mapping.

I hope it will be helpful !!

Hoffman answered 21/5, 2013 at 13:30 Comment(2)
Thanks for this! Any idea how to use any of these methods in a titanium alloy app?Pansophy
What if we have to zoom the image and get pixel? Does it return same color?Jostle
F
8

You can still use buttons.

You can place them over your image in the correct spots and make them invisible.

In XML

<Button android:visibility="invisible"/>

Or

Button mybutton = (Button) v1;
mybutton.setVisibility(View.INVISIBLE);
Fortunia answered 30/8, 2013 at 13:13 Comment(3)
I have a relative layout with some buttons in it. If I set a background image on the relative layout and the buttons to invisible, then the onClick doesn't get triggered. When I set them to visible, they do.Filaria
Wouldn't this depend on how you are making your buttons invisible? I.e., if you are setting the visibility attribute to gone (or invisible) then they can't be clicked, but what if you tried making the background of the button 100% transparent - I expect you would still get a click event(??)Appreciable
@Fortunia I like this solution but visibility didn't work. I made the background transparent and it worked.Talkative
C
3

I had the same challenges and solved it with the library "PhotoView", where you can listen for

onPhotoTap(View view, float x, float y){} 

events and check if the tab is inside your image area, and then perform certain tasks.

I created a library to to help other developers implement such functionality much faster. It's on Github: ClickableAreasImages

This library lets you define clickable areas in an image, associate objects to it and listen for touch events on that area.

How To Use the library:

public class MainActivity extends AppCompatActivity implements OnClickableAreaClickedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Add image
        ImageView image = (ImageView) findViewById(R.id.imageView);
        image.setImageResource(R.drawable.simpsons);

        // Create your image
        ClickableAreasImage clickableAreasImage = new ClickableAreasImage(new PhotoViewAttacher(image), this);

        // Initialize your clickable area list
        List<ClickableArea> clickableAreas = new ArrayList<>();

        // Define your clickable areas
        // parameter values (pixels): (x coordinate, y coordinate, width, height) and assign an object to it
        clickableAreas.add(new ClickableArea(500, 200, 125, 200, new Character("Homer", "Simpson")));
        clickableAreas.add(new ClickableArea(600, 440, 130, 160, new Character("Bart", "Simpson")));
    }

    // Listen for touches on your images:
    @Override
    public void onClickableAreaTouched(Object item) {
        if (item instanceof Character) {
            String text = ((Character) item).getFirstName() + " " + ((Character) item).getLastName();
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        }
    }
...
}
Chino answered 23/1, 2016 at 15:17 Comment(1)
What if I need to check for clicks in non rectangular shaped areas, like circles? Does it work with your library? Thanks.Exile
G
1

If clicking rectangles is enough, then this can be achieved quite easily by extending ImageView. The following is a simple implementation, without regard to accessibility.

The View:

package com.example.letzterwille.views;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.Nullable;

public class ClickableAreaImageView extends ImageView {

    Map< Rect, Runnable > areaEffects = new HashMap<>();

    public ClickableAreaImageView( Context context ) {
        super( context );
    }

    public ClickableAreaImageView( Context context, @Nullable AttributeSet attrs ) {
        super( context, attrs );
    }

    public ClickableAreaImageView( Context context, @Nullable AttributeSet attrs, int defStyleAttr ) {
        super( context, attrs, defStyleAttr );
    }

    public ClickableAreaImageView( Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes ) {
        super( context, attrs, defStyleAttr, defStyleRes );
    }

    public void addAreaEffect( Rect target, Runnable event ) {
        areaEffects.put( target, event );
    }

    @Override
    public boolean onTouchEvent( MotionEvent event ) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN ) {
            int x = ( int ) event.getX();
            int y = ( int ) event.getY();

            for ( Map.Entry< Rect, Runnable > entry : areaEffects.entrySet() ) {
                Rect rect = entry.getKey();
                if ( rect.contains( x, y ) ) entry.getValue().run();
            }
        }

        return super.onTouchEvent( event );
    }
}

In your XML or Java, use it like a normal ImageView.

Then, you have to register the click actions. I wanted to go to specific activities, which looked like this in Kotlin:

class MenuSelection : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_menu_selection)
        val areaImage = findViewById<ClickableAreaImageView>(R.id.menuSelectionImage)

        areaImage.addAreaEffect(Rect(530, 100, 1080, 800), makeRunnable(SettingsActivity::class.java))
        areaImage.addAreaEffect(Rect(30, 80, 430, 700), makeRunnable(StatsActivity::class.java))
    }

    private fun makeRunnable(activity: Class<*>): Runnable {
        return Runnable {
            val intent = Intent(this, activity)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top);
        }
    }
}

In general, use it by defining rectangles, a Runnable to execute when the rectangle is clicked and then add them to the view via ClickableAreaImageView.addAreaEffect

Greenhorn answered 6/3, 2019 at 16:57 Comment(1)
Great example. Thanks. why mix java and kotlin. It makes it more complicated than necessary.Tracytrade
M
0

Improving @sealz reply, here my answer:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_centerInParent="true"
        android:layout_alignTop="@+id/mail"
        android:layout_alignBottom="@+id/mail"
        >
        <Button
            android:id="@+id/leftMail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight=".5"
            android:background="@android:color/transparent"
            />
        <Button
            android:id="@+id/rightMail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight=".5"
            android:background="@android:color/transparent"    
            />
        </LinearLayout>
    <ImageView 
       android:id="@+id/mail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/mail1600x600"
        android:layout_centerInParent="true"
        />
</RelativeLayout>
Mathildamathilde answered 16/2, 2017 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.