Google Maps API v2中自定义颜色的可绘制标记作为地图标记 - Android

4
在Google Maps API v2中是否可以设置自定义颜色的标记?我有一个白色的可绘制资源,想要对其应用颜色过滤器。我尝试了以下代码:
String color = db.getCategoryColor(e.getCategoryId());
Drawable mDrawable = this.getResources().getDrawable(R.drawable.event_location); 
mDrawable.setColorFilter(Color.parseColor(Model.parseColor(color)),Mode.SRC_ATOP);
map.addMarker(new MarkerOptions().position(eventLocation)
    .title(e.getName()).snippet(e.getLocation())
    .icon(BitmapDescriptorFactory.fromBitmap(((BitmapDrawable) mDrawable).getBitmap())));

但是它不起作用。它只显示白色标记而没有自定义颜色。我传递给setColorFilter()的"color"字符串的值是"#RRGGBB"格式。

1个回答

15

我在这里找到了答案:https://groups.google.com/forum/#!topic/android-developers/KLaDMMxSkLs。应用于Drawable的ColorFilter并没有直接应用于Bitmap,而是应用于用于渲染Bitmap的Paint。因此,修改后的可工作代码如下:

String color = db.getCategoryColor(e.getCategoryId());
Bitmap ob = BitmapFactory.decodeResource(this.getResources(),R.drawable.event_location);
Bitmap obm = Bitmap.createBitmap(ob.getWidth(), ob.getHeight(), ob.getConfig());
Canvas canvas = new Canvas(obm);
Paint paint = new Paint();
paint.setColorFilter(new  PorterDuffColorFilter(Color.parseColor(Model.parseColor(color)),PorterDuff.Mode.SRC_ATOP));
canvas.drawBitmap(ob, 0f, 0f, paint);

现在我们可以将obm添加为有颜色的地图标记:

map.addMarker(new MarkerOptions().position(eventLocation)
    .title(e.getName()).snippet(e.getLocation())
    .icon(BitmapDescriptorFactory.fromBitmap(obm)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接