【问题标题】:Android Google Maps: Custom marker for gradient colorAndroid Google Maps:渐变颜色的自定义标记
【发布时间】:2018-03-26 05:08:01
【问题描述】:

我有一个简单的 Android 应用程序,它带有显示当前默认标记的 Google 地图。好消息是我可以简单地更改标记的颜色/色调,在我的情况下,这取决于标记“过期”的时间

bitmapDescriptor = BitmapDescriptorFactory.defaultMarker(this.calculateMarkerHue(msg));

MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(...))
                .icon(bitmapDescriptor)
                .title("Title")
                .snippet("Snippet");


private float calculateMarkerHue(Message msg) {
    float hue = <calculate some value 0.0..360.0 depending on msg>
    return hue;
}

这工作得很好。但是,现在我想使用自定义标记来支持不同类型的标记。虽然我设法使用其他 PNG 可绘制对象更改了标记形状,但我没有成功对颜色进行任何更改。 (不同类型的)可绘制对象、位图、画布、位图描述符的整个概念......我无法理解。

我尝试了各种我在网上找到的东西,但都没有奏效。要么我得到了转换错误、空指针异常,要么没有错误但没有关于设置颜色的影响。

【问题讨论】:

    标签: android google-maps google-maps-api-3 bitmap google-maps-markers


    【解决方案1】:

    尝试添加可绘制对象并通过画布进行绘制,例如:

    markerOptions.icon(bitmapFromDrawable(getActivity(), R.drawable.your_gradient));
    

    bitmapFromDrawable 应该是这样的:

     private BitmapDescriptor bitmapFromDrawable(Context context, int vectorResId) {
            Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
            vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
            Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            vectorDrawable.draw(canvas);
            return BitmapDescriptorFactory.fromBitmap(bitmap);
        }
    

    【讨论】:

    • 那行得通。我只将vectorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); 添加到函数中,其中color 是我计算并提供给函数的int 参数。唯一的问题是它改变了整个 Drawable 的颜色......正如预期的那样。默认标记有一个很好的特性,改变颜色不会影响标记的黑色边框和中心点。
    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多