在Google Maps API v2 Demo 中有一个MarkerDemoActivity 类,您可以在其中查看如何将自定义图像设置为GoogleMap。
// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
由于这只是将标记替换为图像,因此您可能希望使用Canvas 来绘制更复杂和更精美的东西:
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas1 = new Canvas(bmp);
// paint defines the text color, stroke width and size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);
// modify canvas
canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.user_picture_image), 0,0, color);
canvas1.drawText("User Name!", 30, 40, color);
// add marker to Map
mMap.addMarker(new MarkerOptions()
.position(USER_POSITION)
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
// Specifies the anchor to be at a particular point in the marker image.
.anchor(0.5f, 1));
这会将画布canvas1 绘制到GoogleMap mMap 上。代码应该(大部分)不言自明,那里有很多教程如何绘制Canvas。您可以先查看 Android 开发者页面中的 Canvas and Drawables。
现在您还想从 URL 下载图片。
URL url = new URL(user_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
您必须从后台线程下载图像(您可以为此使用AsyncTask 或Volley 或RxJava)。
之后,您可以将BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image) 替换为您下载的图片bmImg。