带有可点击区域的可缩放 SVG - Android

Ale*_*dar 5 svg android svg-android motionevent touchimageview

我正在制作非常简单的应用程序。它需要显示一个包含广义世界地图的 SVG。通过单击城市名称(svg 矩形),我需要显示与该城市对应的另一个 SVG。此外,所有 SVG 都必须支持缩放和平移。

我设法让 SVG 支持缩放和平移,效果很好。为此,我使用svg-android库来渲染SVG,并使用定制的TouchImageView进行平移、缩放和捕获缩放和触摸事件。但是,在 Android 中的 SVG 上制作可点击区域似乎是不可能的。

我尝试了蛮力,在每次用户交互(触摸或缩放)和每次点击 SVG 时重新计算我感兴趣区域的位置,以检查我的区域(矩形列表)是否包含该点,并执行相应的操作。

这不起作用,因为我无法理解计算规则MotionEvent#getX/Y和类似方法。也许我可以为固定 SVG 实现这一点,但对于可缩放,我真的不能。

任何提示?这在Android中甚至可能吗?

Ale*_*dar 5

首先,非常抱歉这么晚才回复。希望对每个人来说还不算太晚:)

用代码示例创建了一个 GitHub 存储库(不是工作应用程序),所以请使用它!:)

使用 repo 的自述文件了解一些详细信息。

核心解决方案:

SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.world_map);

// Get image view (this is our SVG map that is going to be clickable and zoomable):
ImageView touchImageView = (ImageView) view.findViewById(R.id.touchImageView);

// Create drawable (will convert svg to drawable so we can set it to image view as a bitmap):
PictureDrawable image = svg.createPictureDrawable();
Bitmap b = drawableToBitmap(image); // refer to WorldMapFragment for source code of the converting method 
touchImageView.setImageBitmap(b);

// Create image with clickable areas from previous image view and set listener to id (listener of type OnClickableAreaClickedListener created in onAttach callback):
ClickableAreasImage clickableAreasImage = new ClickableAreasImage(new PhotoViewAttacher(touchImageView), listener);

// Define your clickable areas
// parameter values (pixels): (x coordinate, y coordinate, width, h eight) and assign an object to it
List<ClickableArea> clickableAreas = new ArrayList<>();
Map<String, FintemCity> cities = svg.getCities();
for (String key : cities.keySet()){
  clickableAreas.add(cities.get(key).toClickableArea(getMetrics()));
}

// Set your clickable areas to the image
clickableAreasImage.setClickableAreas(clickableAreas);
Run Code Online (Sandbox Code Playgroud)

感谢投票!:)