具有可点击区域的Zoomable SVG - Android

时间:2016-12-18 18:59:17

标签: android svg motionevent touchimageview svg-android

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

我设法让SVG支持缩放和平移,这非常有效。为此,我使用svg-android库来渲染SVG,并使用自定义TouchImageView来平移,缩放和捕获缩放和触摸事件。但是,似乎无法在Android中为SVG制作可点击区域。

我尝试蛮力,重新计算我的有趣区域在每个用户交互(触摸或按比例)上的位置以及每次点击SVG以检查我的区域(矩形列表)是否包含该点,并执行相应的动作。

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

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

1 个答案:

答案 0 :(得分:1)

首先,对于迟到的答案真的很抱歉。希望对每个人来说都不晚:)

我制作了GitHub repo with code sample(没有使用工作应用),请使用它! :)

使用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);

投票表示赞赏! :)