无法将Bitmap转换为Drawable,为什么我会收到此错误?

时间:2012-03-15 00:09:47

标签: java android bitmap drawable

我花了大约3个小时试图解决这个问题,看起来很简单,但我似乎无法解决这个问题!请有人帮帮我!我只想让它显示可绘制资源文件夹中的图像。它说“无法从Bitmap转换为Drawable”。

package com.CS3040.Places;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.CS3040.*;
import com.CS3040.Coursework.R;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class PlaceOverlayItem extends OverlayItem {
    private final GeoPoint point;
    private final Place place;
    private final Drawable marker;
    //private final Context context;

    public PlaceOverlayItem(Context context, Place p, String type) {
        super(p.getGeoPoint(), p.getName(), p.getFormatted_address());

        if(type.equals("restaurant"))
        { 
            //this.marker =
            Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.restaurant);
            this.marker = bmp;

        } 

        //super.setMarker(this.marker);
        this.point = p.getGeoPoint();
        this.place = p;
    }

    /**
     * @return the point
     */
    public GeoPoint getPoint() {
        return point;
    }

    /**
     * @return the place
     */
    public Place getPlace() {
        return place;
    }

    }

3 个答案:

答案 0 :(得分:1)

嗯,这是正确的 - Bitmap 扩展Drawable。我没有做任何Android开发,但听起来你想要一个BitmapDrawable

Resources resources = context.getResources();
Bitmap bmp = BitmapFactory.decodeResource(resources, R.drawable.restaurant);
this.marker = new BitmapDrawable(resources, bmp);

答案 1 :(得分:0)

您需要将您的资源作为Drawable:

if(type.equals("restaurant"))
{ 
    this.marker = context.getResources().getDrawable(R.drawable.restaurant);
} else {
    // marker would get no value without that else case - not allowed if you declare it final
    this.marker = null;
}

答案 2 :(得分:0)

改变这个:

Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.restaurant);
this.marker = bmp;

到此:

Drawable d = context.getResources().getDrawable(R.drawable.restaurant);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
this.marker = d;