グラフィック
■Canvasによる描画
1.Viewクラスを継承したクラスの作成
- パッケージ名を右クリックし、[New]-[Class]
- Superclassに android.view.View 、Nameに新たなクラス名(例:DrawView)
2.アクティビティで新たなビューを表示
setContentView(new DrawView(this));
3.onDrawのオーバーライド
- 新たに作成したクラスを右クリックし[Source]-[override/implement methods]
- 「onDraw」にチェックしOK
4.onDraw内にソースを記述
例: Paint paint = new Paint(); paint.setColor(Color.rgb(255, 0, 0)); paint.setStrokeWidth(1); canvas.drawLine(0, 0, 100, 100, paint);
◇Paintクラス メソッド
setColor(色) | 色の設定 |
setStrokeWidth(太さ) | 線の太さの設定 |
setStyle(スタイル) | 塗りつぶし形式 Paint.Style.STROKE またはPaint.Style.FILL |
setTextSize(サイズ) | 文字サイズの設定(sp) |
setAntiAlias(boolean) | アンチエイリアス |
◇Canvasクラス メソッド
drawColor(色) | 塗りつぶし |
translate(x,y) | キャンバスの移動 |
drawLine(sx, sy, ex, ey, paint) | 線の描画 |
drawCircle(x,y,半径,paint) | 円の描画 |
drawRect(left, top, right, bottom, paint) | 四角形の描画 |
drawText(文字列, x, y, paint) | 文字列の描画 |
■SurfaceView
高速な描画を行う。
android.view.SurfaceView を継承しクラスを作成。後はCanvasの時と同様に作成。
SurfaceView を継承したクラスに implements SurfaceHolder.Callback を追加。
必要なオーバーライドを行い、コンストラクタで以下を行う。
getHolder().addCallback(this);
surfaceCreated 内で以下のように描画を行う。
public void surfaceCreated(SurfaceHolder holder) { Canvas canvas = holder.lockCanvas(); Paint paint = new Paint(); canvas.drawColor(Color.WHITE); paint.setColor(Color.BLUE); paint.setAntiAlias(true); paint.setTextSize(24); canvas.drawText("ABCDE", 0, 100, paint); holder.unlockCanvasAndPost(canvas); }