8

我正在尝试为我的地图集群设置视图。我正在从 XML 膨胀视图并根据集群大小设置文本,我想显示该视图。在下面的代码中,我得到一个空位图作为回报:

private Bitmap createClusterBitmap(int clusterSize) {
    View cluster = LayoutInflater.from(context).inflate(R.layout.map_cluster, null);        
    cluster.setText(String.valueOf(clusterSize));
    cluster.setDrawingCacheEnabled(true);
    cluster.buildDrawingCache(true);
    Bitmap bm = cluster.getDrawingCache();
    return bm;
}

在下面的代码中,我在第四行得到空指针(布局参数):

private Bitmap createClusterBitmap(int clusterSize) {
    View cluster = LayoutInflater.from(context).inflate(R.layout.map_cluster, null);
    TextView clusterSizeText = (TextView) cluster.findViewById(R.map.cluster);
    clusterSizeText.setText(String.valueOf(clusterSize));
    Bitmap clusterBitmap = Bitmap.createBitmap( cluster.getLayoutParams().width, cluster.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas clusterCanvas = new Canvas(clusterBitmap);
    cluster.layout(cluster.getLeft(), cluster.getTop(), cluster.getRight(), cluster.getBottom());
    cluster.draw(clusterCanvas);
    return clusterBitmap;
}

当将其更改为以下代码时,我没有收到错误,但没有绘制任何内容:

private Bitmap createClusterBitmap(int clusterSize) {
    View cluster = LayoutInflater.from(context).inflate(R.layout.map_cluster, null);
    TextView clusterSizeText = (TextView) cluster.findViewById(R.map.cluster);
    clusterSizeText.setText(String.valueOf(clusterSize));
    Bitmap clusterBitmap = Bitmap.createBitmap( 50,50 , Bitmap.Config.ARGB_8888);                
    Canvas clusterCanvas = new Canvas(clusterBitmap);
    cluster.layout(50, 50, 50, 50;
    cluster.draw(clusterCanvas);
    return clusterBitmap;
}

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+map/cluster"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/map_pointer_cluster"
    android:gravity="center"
    android:orientation="vertical"
    android:textColor="@android:color/black"
    android:textSize="35dp"
    android:textStyle="bold" />
4

1 回答 1

24

cluster.getLayoutParams()的大概是null。首先,您需要测量膨胀视图的宽度/高度,然后分配给它。如下所示:

private Bitmap createClusterBitmap(int clusterSize) {
    View cluster = LayoutInflater.from(context).inflate(R.layout.map_cluster,
            null);

    TextView clusterSizeText = (TextView) cluster.findViewById(R.id.map_cluster_text);
    clusterSizeText.setText(String.valueOf(clusterSize));

    cluster.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    cluster.layout(0, 0, cluster.getMeasuredWidth(),cluster.getMeasuredHeight());

    final Bitmap clusterBitmap = Bitmap.createBitmap(cluster.getMeasuredWidth(),
            cluster.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(clusterBitmap);
    cluster.draw(canvas);

    return clusterBitmap;
}
于 2012-09-13T12:36:11.203 回答