从一个文件夹加载和绘制图像到android

时间:2013-12-20 21:38:48

标签: java android bitmap

我正在尝试在我的Android应用中绘制背景图片。但是,当我尝试将其绘制为位图时,它表示找不到该文件。您可以使用项目目录中创建的自定义文件夹中的图像吗?

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
    Bitmap BackgroundImage;

    private static final String TAG = MainGamePanel.class.getSimpleName();

    private MainThread thread;

    public MainGamePanel(Context context) {
        super(context);

        // adding the callback (this) to the surface holder to intercept events
        getHolder().addCallback(this);

        // creating game thread
        thread = new MainThread(getHolder(), this);

        //   make the GmaePanel focusable so it can handle events
        setFocusable(true);
    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        thread.setRunning(true);
        thread.start();

        Background b1 = new Background();

            BackgroundImage = b1.loadBackgroundImage();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        Log.d(TAG, "Surface is being destroyed");
        boolean retry = true;
        while(retry){
            try{
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
                // try again to shutdown thread
            }

        }
        Log.d(TAG, "Thread was shut down cleanly");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawBitmap(BackgroundImage, 0, 0, null);


    }



}

------背景类------

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Background {
    private String imageLoc;

    public Background(){


    }

    public String getImageLoc() {
        return imageLoc;
    }

    public void setImageLoc(String imageLoc) {
        this.imageLoc = imageLoc;
    }

    public Bitmap loadBackgroundImage(){
        Bitmap background = BitmapFactory.decodeFile("/Users/Justin/Documents/Project_WinterGalaxy/AndroidGalaxy/images/Background.png");   

        return background;
    }



}

1 个答案:

答案 0 :(得分:1)

在代码中显示图像的方法是:将其放在相关的drawable文件夹中,然后像这样加载:

Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.Background);