我正在尝试在我的应用中添加对平板电脑的支持,并遇到这行代码抛出的IllegalArgumentException:
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_green_10by19))
方法.fromResource可以从图像文件(png)中使用R.drawable.arrow_green_10by19,但是当用矢量文件arrow_green_10by19.xml(在Android Studio IDE中渲染得很好)替换png时,它会生成一个运行时如上所述。
有人知道如何在BitmapDescriptorFactory中实现矢量资源并可以帮助我吗?
感谢。
答案 0 :(得分:14)
我遇到了同样的问题,但我意识到在我的设备上使用API 16它运行正常但是使用API 21它会崩溃。最后,它使用this solution在两个设备中都有效。代码如下:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
和此:
private static Bitmap getBitmap(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return BitmapFactory.decodeResource(context.getResources(), drawableId);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
所以我以这种方式结合了这两个功能:
private Marker addMark(LatLng latLng, String title) {
Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_place_24dp);
Marker marker = googleMap.addMarker(new MarkerOptions().position(latLng)
.title(title)
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.draggable(true));
return marker;
}
其中R.drawable.ic_place_24dp
是矢量资产(.xml),而不是.png