【问题标题】:Use Layout as OverlayItem on MapView?在 MapView 上使用布局作为 OverlayItem?
【发布时间】:2010-07-23 20:19:20
【问题描述】:

是否可以将 XML 中定义的布局用作要添加到 MapView 而不是单个可绘制对象的 OverlayItem?我在地图上绘制了几个叠加层,但它们只是单个图像,我现在想放置更复杂的对象而不是简单的可绘制对象的叠加层。

我打算画一个里面有动态图像的标记(只是一个朋友定位器类型的东西),每个标记里面都有不同的图片。

将这些作为 OverlayItems 添加是解决方法,还是我需要将每个作为子视图添加到 MapView(这似乎效率低下)?

【问题讨论】:

    标签: android overlay android-mapview


    【解决方案1】:

    我正在尝试做类似的事情 - 将带有自定义视图的 Google 地图样式气球绘制到地图上。我尝试覆盖 OverlayItem 的 draw(),并以这种方式绘制我在 XML 中定义的布局。问题在于将 View 转换为 Drawable 以绘制到 MapView 画布上,这意味着我失去了 Layout 的所有事件处理功能,因此按钮等无法正常工作。如果您没有担心图像上的任何事件,那么这可以工作,您只需要使用当前 Activity 的 LayoutInflater (activity.getLayoutInflater()) 为您的视图充气,按照下面的描述进行测量和布局android 开发者网站上的“Android 如何绘制视图”页面(由于新的用户限制,无法发布链接,抱歉!),最后在您的视图上调用 buildDrawingCache() 和 getDrawingCache() 以将其作为位图获取。然后可以通过您构建的 Overlay 子类的 draw() 方法将其绘制到 Canvas 上。

    最后,我实际上采用了您建议的第二种方法(将每个作为子视图添加到 MapView,使用 MapView.LayoutParams 将布局悬停在相关的 OverlayItem 上)。虽然我只有一个孩子的观点需要担心,所以我不太担心这里的效率,如果这实际上是值得关注的事情,这对你来说可能是一个更大的问题(虽然它可能值得首先测试)。我在here 所做的事情有一个小记录,其中包含更多细节。

    最后你可能想看看android-mapviewballoons 的处理方法,非常值得一看。

    【讨论】:

      【解决方案2】:

      通过将布局转换为可绘制对象,我能够将布局添加为地图上的标记。这是取自this tutorialbitmapFromView 函数:

      public static Bitmap bitmapFromView(View layout, int width, int height, Context context) {
          // Create a new bitmap and a new canvas using that bitmap
          Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
          Canvas canvas = new Canvas(bmp);
          layout.setDrawingCacheEnabled(true);
          // Supply measurements
          layout.measure(View.MeasureSpec.makeMeasureSpec(canvas.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(canvas.getHeight(), View.MeasureSpec.EXACTLY));
          // Apply the measures so the layout would resize before drawing.
          layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());
          // and now the bmp object will actually contain the requested layout
          canvas.drawBitmap(layout.getDrawingCache(), 0, 0, new Paint());
          return bmp;
      }
      

      我使用该方法将位图添加为这样的标记:

      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View layout = inflater.inflate(R.layout.MY_LAYOUT, null);
      Bitmap markerBitmap = bitmapFromView(layout, MY_WIDTH, MY_HEIGHT, context);
      
      MarkerOptions markerOptions = new MarkerOptions()
                  .title(MY_TITLE)
                  .position(MY_POSITION)
                  .icon(BitmapDescriptorFactory.fromBitmap(markerBitmap));
      map.addMarker(markerOptions);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        • 1970-01-01
        • 2013-09-01
        • 1970-01-01
        • 2016-10-23
        相关资源
        最近更新 更多