首页 > 解决方案 > Android 在 ImageView 上绘制固定路径,支持多屏

问题描述

我有大陆图片,当用户点击图片时我需要检测他点击了哪个大陆。

我尝试为每个大陆收集 xy 坐标,当用户单击图像时,我检查用户手指 xy 是否存在于我的路径中,如下所示:

val path = Path()
path.moveTo(409f, 1986f)
path.lineTo(414f, 1986f)
path.lineTo(418f, 1986f)
...
path.close()

val rectF = RectF()
path.computeBounds(rectF, true)
val r = Region()
r.setPath(path, Region(rectF.left.toInt(), rectF.top.toInt(), rectF.right.toInt(), rectF.bottom.toInt()))

ivMainMap?.setOnTouchListener { v, event ->
    val point = Point()
    point.x = event.x.toInt()
    point.y = event.y.toInt()
    if (r.contains(point.x, point.y)) {
        Toast.makeText(this, "South America", Toast.LENGTH_LONG).show()
    }
    return@setOnTouchListener true
}

但我遇到了多个屏幕尺寸的问题,之后我尝试在 560 dpi 屏幕上收集 xy 坐标,并将 xy 转换为具有当前屏幕尺寸密度的新 xy,如下所示:

private fun getExactX(x: Float): Float {
    val screenAdjust = Resources.getSystem().displayMetrics.densityDpi.toFloat() / 560f
    return ((x) * screenAdjust)
}

private fun getExactY(y: Float): Float {
    val screenAdjust = Resources.getSystem().displayMetrics.densityDpi.toFloat() / 560f
    return ((y) * screenAdjust)
}

但问题仍然存在

大陆图片

标签: androidkotlinandroid-imageview

解决方案


创建一个比率乘数:

DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    screen_width = displayMetrics.widthPixels;
    ratio_multiplier = screen_width/720; // Or whatever your base screen size is.

Then that ratio_multiplier can be used for anything that needs resizing.
I use this in all my programs for resizing button, images, etc.

推荐阅读