*このページは web-dou.com のアーカイブです。(2025年 サイト統合)

Android 高速な描画処理(SurfaceView)

TOP > Androidアプリ開発日誌 >  高速な描画処理(SurfaceView)  >  サンプルコード

円とテキストを常に(100,100)周辺にランダムに描画するSurfaceViewのサンプルコード(Android)

SurfaceViewの見本 円とテキストを常に(100,100)周辺にランダムに描画するSurfaceViewのサンプルコード
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package jp.mediawing.android.test2;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
 
import android.util.Log;
import java.util.Random;
 
import android.graphics.Color;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
 
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
 
        //レイアウトファイルでなく カスタムクラスを使用。
        //setContentView(R.layout.main);
        setContentView(new SurfaceTestView(this));
    }
 
    @Override
    protected void onDestroy() {
        // 後処理
        super.onDestroy();
        Thread.interrupted();
    }
 
    // SurfaceViewをextends したカスタムクラス
    class SurfaceTestView extends SurfaceView implements Runnable {
        private Thread thread ;
        private int x = 100 ;
        private int y = 100 ;
 
        public SurfaceTestView(Context context) {
            super(context);
 
            thread = new Thread(this); // スレッドの作成
            thread.start(); // run() の実行
        }
 
        @Override
        public void run() {
            while (true) {
                draw(); // draw() の実行
            }
        }
 
        public void draw() {
            Canvas canvas = getHolder().lockCanvas();
            if (canvas != null) {
                // キャンバスを真っ黒に
                canvas.drawColor(Color.BLACK);
 
                // 円の座標をランダムに変更
                Random rnd = new Random();
                int ran = rnd.nextInt(4);
                if ( ran == 0 ) x = x+1 ;
                if ( ran == 1 ) x = x-1 ;
                if ( ran == 2 ) y = y+1 ;
                if ( ran == 3 ) y = y-1 ;
 
                // 円を描画
                Paint paint = new Paint();
                paint.setAntiAlias(true);
                paint.setColor(Color.RED);
                canvas.drawCircle(x, y, 10.0f, paint);
 
                // テキストを描画
                paint.setTextSize(14);
                paint.setColor(Color.RED);
                canvas.drawText("x=" + x + " y=" + y , x , y+20, paint);
 
                getHolder().unlockCanvasAndPost(canvas);
            }
        }
    }
}