【问题标题】:Best solution to draw responsive areas on image在图像上绘制响应区域的最佳解决方案
【发布时间】:2023-03-14 19:00:02
【问题描述】:

我想知道获得以下结果的最佳解决方案是什么。 这是我到目前为止发现的:

一个用于森林的 ImageView 和一个透明的 surfaceView(用于处理触摸),我将在其上绘制矩形? 要么... 只有一个 SurfaceView,图像设置为背景,矩形直接绘制在...上?

对于这 2 个,我已经选择了一个 RelativeLayout。

这 2 个中的哪一个是最有效和最容易做到的? 或者也许还有另一种我没有想到的方法。

无论如何感谢您的建议,这就是我倾向于...

【问题讨论】:

标签: android view


【解决方案1】:

我通过将图像放置在 RelativeLayout 中来实现这一点(FrameLayout 也可以),然后以编程方式添加每个轮廓视图。如果您知道 x 和 y 原点(可能是与图像的比率)和每个区域的大小,您可以轻松地为每个视图/区域充气(带有黑色边框,透明中心),使其可点击并设置监听器,然后通过调整它的边距来设置它的原点。您可能希望在图像完成布局后执行所有这些操作:

我把它放在我的FragmentonActivityCreated 中,但其他生命周期方法也可以工作......

ViewTreeObserver vto = image.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            if (image.getMeasuredHeight() > 0) {
                addHotSpots();
                ViewTreeObserver obs = image.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
            }
        }

    });

这就是我实际放置所有热点/区域的方式:

protected void addHotSpots() {
    HotSpot[] hotSpots = res.hotspots;
    for (HotSpot hs : hotSpots) {
        addHotSpotToImage(hs);

}

private void addHotSpotToImage(HotSpot hs) {

    int height = image.getMeasuredHeight();
    int width = image.getMeasuredWidth();
    //this piece will probably be different for you
    //depending on what you know about the area's intended size/position
    double hsHeightRatio = hs.lr.y - hs.ul.y;
    double hsWidthRatio = hs.lr.x - hs.ul.x;
    double leftMargin = hs.ul.x * width;
    double topMargin = hs.ul.y * height;
    double hsHeight = height * hsHeightRatio;
    double hsWidth = width * hsWidthRatio;
    LayoutInflater vi = (LayoutInflater) image.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View newSpot = vi.inflate(R.layout.question_hotspot, null);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) hsWidth, (int) hsHeight);
    newSpot.setTag(hs.key);
    newSpot.setFocusable(true);
    newSpot.setClickable(true);
    newSpot.setFocusableInTouchMode(true);
    newSpot.setOnTouchListener(this);

    params.topMargin = (int) topMargin;
    params.leftMargin = (int) leftMargin;
    image.addView(newSpot, params);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多