我的Drawable文件夹中有一个png图像。我在许多标记中使用相同的图像,但尺寸不同。我想要在Drawable文件夹中创建重复使用原始图像的XML,而不是创建许多不同大小的图像。
我尝试了这个答案的解决方案:Scale a drawable resource in XML (Android)但它们在我的情况下不起作用。当我到达
BitmapDescriptor scaledIcon = BitmapDescriptorFactory.fromResource(R.drawable.scaled_marker_image); //scaled_marker_image is the XML that resize the original image
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Marker").icon(scaledIcon));
基本上在MarjerOptions().icon(scaledIcon)
我得到nullPointerException
任何想法如何实现这一目标?
答案 0 :(得分:0)
XML看起来像这样(如Scale a drawable resource in XML (Android)回答中所示)
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/marker_image"
android:insetTop="30dp"
android:insetLeft="10dp"
android:insetRight="10dp"
android:insetBottom="0dp"
/>
我们定义了一个将Drawable转换为Bitmap的方法
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
然后,将drawable设置为标记:
Drawable drawable = getResources().getDrawable(getResources().getDrawable(R.drawable.mi_posicion_marker2));
BitmapDescriptor scaledIcon = BitmapDescriptorFactory.fromBitmap(drawableToBitmap(drawable));
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Marker").icon(scaledIcon));