###前提・実現したいこと
timer, handler とinvalidate()を使用しCanvas で描画した画像を動的にクリアーして再描画したいです。
なぜできないのかわからないので指摘してほしいです。
###該当のソースコード
java
1 2 3package com.example.naka.myapplication5; 4 5import android.os.Bundle; 6import android.os.Handler; 7import android.support.v7.app.AppCompatActivity; 8 9import java.util.Timer; 10import java.util.TimerTask; 11 12 13public class MainActivity extends AppCompatActivity { 14 private TestView testView; 15 private Timer timer; 16 private int pos = 0; 17 private int period = 10000; 18 private final Handler handler = new Handler(); 19 20 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 // View の設定 25 testView = new TestView(this); 26 setContentView(testView); 27 28 // TimerTask の設定 29 timer = new Timer(false); 30 timer.schedule(new TimerTask() { 31 public void run() { 32 handler.post(new Runnable() { 33 public void run() { 34 // position移動 35 pos += 1; 36 testView.setPositon(pos); 37 // 再描画のために無効にする 38 testView.invalidate(); 39 } 40 }); 41 } 42 },0, period); 43 44 } 45 46 private void stopTimerTask(){ 47 timer.cancel(); 48 timer = null; 49 } 50}
java
1package com.example.naka.myapplication5; 2 3import android.content.Context; 4import android.content.res.Resources; 5import android.graphics.Bitmap; 6import android.graphics.BitmapFactory; 7import android.graphics.Canvas; 8import android.graphics.Matrix; 9import android.graphics.Paint; 10import android.view.View; 11 12 13 14public class TestView extends View{ 15 16 private int i = 0; 17 private static final int NUM = 3; 18 private Matrix matrix = new Matrix(); 19 private Paint paint = new Paint(); 20 Bitmap bitmap[]; 21 22 23 public TestView(Context context) { 24 super(context); 25 bitmap = new Bitmap[NUM]; 26 27 // リソースから Bitmap を取得 28 Resources r = getResources(); 29 bitmap[0] = BitmapFactory.decodeResource(r, R.drawable.icon); 30 31 // Bitmap のサイズの取得 32 int width = bitmap[0].getWidth(); 33 int height = bitmap[0].getHeight(); 34 35 36 37 matrix = new Matrix(); 38 matrix.postScale(1.3f, 0.9f); // スケールを指定 39 bitmap[1] = Bitmap.createBitmap(bitmap[0], 0, 0, width, height, matrix, true); 40 41 matrix = new Matrix(); 42 matrix.postScale(1.15f, 0.95f); // スケールを指定 43 bitmap[2] = Bitmap.createBitmap(bitmap[0], 0, 0, width, height, matrix, true); 44 } 45 46 @Override 47 public void onDraw(Canvas canvas) { 48 49 for (int i = 0; i < NUM; i++) { 50 // Bitmap の描画 51 canvas.drawBitmap(bitmap[i], i*350, 0, paint); 52 } 53 } 54 public int getPosition() { 55 return i; 56 } 57 58 public void setPositon(int pos) { 59 i = pos; 60 } 61} 62
回答1件
あなたの回答
tips
プレビュー