我需要在运行时计算的 Google map 图标标记。为此,我创建了从 View 派生的类。
class DrawView extends View {
Paint p;
RectF rectf;
String textLabel;
public DrawView(Context context, String text) {
super(context);
p = new Paint();
rectf = new RectF(100,100,300,150);
this.textLabel=text;
}
@Override
protected void onDraw(Canvas canvas) {
p.setColor(Color.RED);
p.setStrokeWidth(10);
canvas.drawRoundRect(rectf, 20, 20, p);
//another draw will be here...
}
}
将 View 转换为位图
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
添加标记
View view =new DrawView(this,"Some text");
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap=loadBitmapFromView(view);
Marker marker=mMap.addMarker(new MarkerOptions().position(new LatLng(s.lat,s.lng)).icon(BitmapDescriptorFactory.fromBitmap(bitmap)));
NPE发生
FATAL EXCEPTION: main
java.lang.NullPointerException
at ru.ch2.activity.CheckInActivity.loadBitmapFromView(CheckInActivity.java:439)
at ru.ch2.activity.CheckInActivity.onMapReady(CheckInActivity.java:254)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:347)
at xk.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.af.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
在loadBitmapFromView就行了
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
最佳答案
尝试使用这个函数:
调用view.measure
强制计算 View 大小以获得正确的 View 大小
public static Bitmap loadBitmapFromView(View view) {
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
关于android - 如何将自定义 View 转换为 Google map 标记图标的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42241658/