Last active
October 25, 2023 00:46
-
-
Save Ozius/1ef2151908c701854736 to your computer and use it in GitHub Desktop.
Get BitmapDescriptor from a VectorDrawable resource for use as an icon on a Google Map Marker. Google Maps SDK for Android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
mMap.addMarker(new MarkerOptions() | |
.position(new LatLng(latitude, longitude)) | |
.title("Marker Title") | |
.snippet("Marker snippet") | |
.icon(getBitmapDescriptor(R.drawable.ic_place_black_48dp))); | |
*/ | |
private BitmapDescriptor getBitmapDescriptor(int id) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { | |
VectorDrawable vectorDrawable = (VectorDrawable) getDrawable(id); | |
int h = vectorDrawable.getIntrinsicHeight(); | |
int w = vectorDrawable.getIntrinsicWidth(); | |
vectorDrawable.setBounds(0, 0, w, h); | |
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); | |
Canvas canvas = new Canvas(bm); | |
vectorDrawable.draw(canvas); | |
return BitmapDescriptorFactory.fromBitmap(bm); | |
} else { | |
return BitmapDescriptorFactory.fromResource(id); | |
} | |
} |
nice one, it helped me a lot. thanks and keep it up.
On API 19 emulator it throws exception: "Caused by: java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized". I think this is because the emulator doesn't contain Google Play Services. So call this method inside onMapReady()
, not onCreateView()
.
excellent!
Kotlin version updated to support calling from anywhere:
fun bitmapDescriptorFromVector(fragmentContext: Context, vectorResId: Int): BitmapDescriptor? =
// Some VectorDrawables do not display when using ContextCompat.
// Either ResourcesCompat or VectorDrawableCompat seem to work.
// VectorDrawableCompat was chosen because it is backed by ResourcesCompat under the hood
VectorDrawableCompat.create(fragmentContext.resources, vectorResId, fragmentContext.theme)?.run {
setBounds(0, 0, intrinsicWidth, intrinsicHeight)
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
draw(Canvas(bitmap))
BitmapDescriptorFactory.fromBitmap(bitmap)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, thanks