简体   繁体   中英

Android Google Maps: Custom marker for gradient color

I have a simple Android app with a Google Map that shows currently default markers. The nice thing is that I can simple change the color/hue of the marker, which in my case depend on the time a marker will "expire"

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

This works perfectly fine. However, now I would like to use custom markers to support different types of markers. While I managed to change the marker shape using other PNG drawables, I didn't succeed to make any changes to the color. The whole notions of (different types of) drawables, bitmaps, canvases, bitmap descriptors...I cannot get my head around.

I've tried all kinds of stuff I found online but nothing worked. Either I got casting errors, null pointer exceptions, or no errors but not effects regarding setting the color.

Try to add drawable and draw it via canvas something like:

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

The bitmapFromDrawable should be like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM