Android: how to make a clickable map image with each country producing a different action?

前端 未结 4 1684
天命终不由人
天命终不由人 2021-01-26 05:42

I need to display a pretty image of a map of Europe, and I want my app to, e.g. bring up a different activity, when the user clicks each country - each country on the map needs

4条回答
  •  粉色の甜心
    2021-01-26 06:13

    I did it with a mask like Scotty indicated, but I ran into more problems. Basically the colors returned by getPixel were slightly different than in the mask file. What I did was to load the mask in memory with scaling disabled and with full color options like this:

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inTargetDensity = 1;
    bitmapOptions.inDensity = 1;
    bitmapOptions.inDither = false;
    bitmapOptions.inScaled = false;
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    mask = BitmapFactory.decodeResource(appContext.getResources(), resMask, bitmapOptions);
    

    Then I looked up the coords from the scaled image like this:

    ImageView map = (ImageView) findViewById(R.id.image);
    Drawable drawable = map.getDrawable();
    Rect imageBounds = drawable.getBounds();
    int scaledHeight = imageBounds.height();
    int scaledWidth = imageBounds.width();
    int scaledImageOffsetX = Math.round(event.getX()) - imageBounds.left;
    int scaledImageOffsetY = Math.round(event.getY()) - imageBounds.top;
    
    int origX = (scaledImageOffsetX * mask.getWidth() / scaledWidth);
    int origY = (scaledImageOffsetY * mask.getHeight() / scaledHeight);
    
    if(origX < 0) origX = 0;
    if(origY < 0) origY = 0;
    if(origX > mask.getWidth()) origX = mask.getWidth();
    if(origY > mask.getHeight()) origY = mask.getHeight();
    

    and then I applied mask.getPixel(origX, origY). It only works when the image is scaled with android:scaleType="fitXY" inside the ImageView otherwise the coords are off.

提交回复
热议问题