Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom coloured drawable as map marker in Google Maps API v2 - Android

Is it possible to set a custom coloured markers in Google Maps API v2? I have a white drawable resource, and I want to apply colour filter to it. I've tried this:

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())));

but it doesn't work. It only shows the white marker without the custom colour. The value of the "color" string that I'm passing to setColorFilter() is in the form of "#RRGGBB".

like image 421
Bojan Ilievski Avatar asked Dec 07 '22 05:12

Bojan Ilievski


1 Answers

I fount the answer here: https://groups.google.com/forum/#!topic/android-developers/KLaDMMxSkLs The ColorFilter you apply to a Drawable isn't applied directly to the Bitmap, it's applied to the Paint used to render the Bitmap. So the modified working code would look like this:

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);

...and now we can add obm as the coloured map marker:

map.addMarker(new MarkerOptions().position(eventLocation)
    .title(e.getName()).snippet(e.getLocation())
    .icon(BitmapDescriptorFactory.fromBitmap(obm)));
like image 54
Bojan Ilievski Avatar answered Jan 03 '23 04:01

Bojan Ilievski