SurfaceViewを用いて簡単なゲームアプリを作成しているのですが、背景が変更できないという問題に当たっています。  
どこに（おそらくはsurfaceCreated（）である。）どんなコードを追加したら、背景を任意の画像に変更できるでしょうか。  
また、背景を黒にする設定はどこにもしていないのですが、これは元々そうなる設定なのですか？

```

    package com.example.ab18.androidgame2d;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.media.AudioAttributes;
    import android.media.AudioManager;
    import android.media.SoundPool;
    import android.os.Build;
    import android.view.MotionEvent;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class GameSurface extends SurfaceView implements SurfaceHolder.Callback {
    
        private GameThread gameThread;
    
        private final List<ChibiCharacter> chibiList = new ArrayList<ChibiCharacter>();
        private  final List<Explosion> explosionList = new ArrayList<Explosion>();
    
        private static final int MAX_STREAMS = 100;
        private int soundIdExplosion;
        private int soundIdBackground;
    
        private boolean soundPoolLoaded;
        private SoundPool soundPool;
    
        private boolean fastTouch = true;
    
        private Paint mPaint = new Paint();
    
        public  GameSurface(Context context) {
            super(context);
    
            // Make Game Surface focusable so it can handle events. . .
            this.setFocusable(true);
    
            // Set callback.
            this.getHolder().addCallback(this);
    
            //self made method
            this.initSoundPool();
        }
    
        private  SurfaceHolder mHolder;
    
        protected  void  onDraw(){
            Canvas canvas = mHolder.lockCanvas();
            mPaint.setTextSize(500);
            mPaint.setColor(Color.WHITE);
            canvas.drawText("Hello Custom View!", 50,50,mPaint);
    
            mHolder.unlockCanvasAndPost(canvas);
        }
    
        private  void initSoundPool() {
    
            // with Android API >= 21
            //Build.VERSION.SDK_INTで機種の番号を取得
            if (Build.VERSION.SDK_INT >= 21) {
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_GAME)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
    
                SoundPool.Builder builder = new SoundPool.Builder();
                builder.setAudioAttributes(audioAttributes).setMaxStreams(MAX_STREAMS);
    
                this.soundPool = builder.build();
    
                // with Android  API < 21
            } else {
                // SoundPool(int maxStreams, int streamType, int srcQuality)
                this.soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
            }
    
            // When SoundPool load complete.
            this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    soundPoolLoaded = true;
    
                    // Playing background sound.
                    playSoundBackground();
                }
            });
    
            // Load the sound background.mp3 into SoundPool
            this.soundIdBackground = this.soundPool.load(this.getContext(), R.raw.background, 1);
    
            // Load the sound explosion.wav int Soundbool
            this.soundIdExplosion = this.soundPool.load(this.getContext(), R.raw.explosion, 1);
        }
    
        public  void playSoundExplosion() {
            if (this.soundPoolLoaded) {
                float leftVolumn = 0.8f;
                float rightVolumn = 0.8f;
                // Play sound explosion.wav(.mp3)
                int streamId = this.soundPool.play(this.soundIdExplosion, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    
        public  void playSoundBackground() {
            if (this.soundPoolLoaded) {
                float leftVolumn = 0.8f;
                float rightVolumn = 0.8f;
                // Play sound background.mp3
                int streamId = this.soundPool.play(this.soundIdBackground, leftVolumn, rightVolumn, 1, -1, 1f);
            }
        }
    
        public  void  update() {
            for (ChibiCharacter chibi: chibiList) {
                chibi.update();
            }
    
            for (Explosion explosion: this.explosionList) {
                explosion.update();
            }
    
            Iterator<Explosion> iterator = this.explosionList.iterator();
            while (iterator.hasNext()) {
                Explosion explosion = iterator.next();
    
                if(explosion.isFinish()){
                    // If explosion finish, Remove the current element from the iterator & list
                    iterator.remove();
                    continue;
                }
            }
        }
    
        @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);
    
            for (ChibiCharacter chibi: chibiList) {
                chibi.draw(canvas);
            }
    
            for (Explosion explosion: this.explosionList) {
                explosion.draw(canvas);
            }
        }
    
        // Implements method of SurfaceHolder.Callback
        @Override
        public void surfaceCreated(SurfaceHolder holder){
    
            //個々の処理が全く聞いていない。なぜか。
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.FILL);
    
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(Color.WHITE);
            canvas.drawCircle(100,200,50,paint);
            holder.unlockCanvasAndPost(canvas);
    
            List<Bitmap> chibiBitmap = new ArrayList<Bitmap>();
            List<ChibiCharacter> chibi = new ArrayList<ChibiCharacter>();
    
            for (int i = 0; i < 100; i++ ) {
                int random = (int) (Math.random() * 100);
                int random2 = (int)(Math.random() * 50);
                Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(), R.drawable.chibi100);
                chibiBitmap.add(chibiBitmap1);
                ChibiCharacter chibi1 = new ChibiCharacter(this, chibiBitmap.get(i), i + random, i + random + random2);
                chibi.add(chibi1);
                this.chibiList.add(chibi.get(i));
            }
    
            this.gameThread = new GameThread(this,holder);
            this.gameThread.setRunning(true);
            this.gameThread.start();
        }
    
        // Implements method of SurfaceHOlder.Callback
        @Override
        public void  surfaceChanged(SurfaceHolder holder, int format, int widht, int height) {
    
        }
    
        // Implements method of SurfaceHolder.Callback
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            while (retry) {
                try {
                    this.gameThread.setRunning(false);
    
                    // Parent thread must wait until the end of GameThread.
                    this.gameThread.join();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
                retry = true;
            }
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int random = (int)(Math.random() * 100);
                int x = (int) event.getX();
                int y = (int) event.getY();
    
                Iterator<ChibiCharacter> iterator = this.chibiList.iterator();
    
                while(iterator.hasNext()) {
                    ChibiCharacter chibi = iterator.next();
                    if (chibi.getX() < x && x < chibi.getX() + chibi.getWidth()
                        && chibi.getY() < y && y < chibi.getY() + chibi.getHeight()) {
                        // Remove the current element from the iterator and the list.
                        iterator.remove();
                        playSoundExplosion();
    
                        // Create Explosion object.
                        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.explosion);
                        Explosion explosion = new Explosion(this, bitmap, chibi.getX(), chibi.getY());
    
                        this.explosionList.add(explosion);
                    }
                }
    
                if (fastTouch){
                    for (ChibiCharacter chibi: chibiList) {
                        int movingVectorX = x + random - chibi.getX() ;
                        int movingVectorY = y + random - chibi.getY() ;
                        chibi.setMovingVector(movingVectorX, movingVectorY);
                    }
    
                    fastTouch = false;
                }
    
                return  true;
            }
    
            return  false;
        }
    }
    
```
CC BY-SA 4.0
2019-12-19T01:04:35.980
61560
2022-12-29T13:00:40.103
2019-12-19T05:42:03.373
37129
37129
question
java android
SurfaceViewの背景画像を真っ黒から任意の画像に変更したい
[SurfaceView](https://developer.android.com/reference/android/view/SurfaceView.html)
には背景画像を設定するような機能は存在しないと思います。  
ゲームのようなものを作成するのであれば毎フレーム、背景も自分で描画してください。コードサンプルのような実装であれば draw(Canvas canvas)
メソッドの ChibiCharacter や Explosion の描画の前に必要に応じて背景画像を描画すればよいかと思います。

> 背景を黒にする設定はどこにもしていないのですが、これは元々そうなる設定なのですか？

コードサンプルの draw()メソッドの最初に super.draw(canvas);
を呼び出しているのでそこでクリアされているのではないかと思います。詳しくは Android のソースコードを読んでみてください。
CC BY-SA 4.0
2019-12-19T07:17:12.413
61574
2019-12-19T07:17:12.413
27410
61560
answer