试图每100毫秒更新一次Bitmap

时间:2017-01-14 01:30:16

标签: android handler runnable

我试图在位图中每隔100毫秒更改一次随机游走中单个像素的颜色。这是我的代码,但是在我点击了应该触发代码的按钮之后,我看到的是对位图的突然改变我尝试更新而不是每100毫秒实时发生变化。

如何实时地每100毫秒更新一次Bitmap,而不是仅仅显示单击按钮时更改的内容?

这是我的代码:

public class MainActivity extends AppCompatActivity {

    private int height;
    private int width;
    Bitmap image;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.bitmap_imageview);
        image = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
        image.eraseColor(getResources().getColor(R.color.verydarkblue));
        imageView.setImageBitmap(image);
        Button press = (Button) findViewById(R.id.press);

        mHandler = new Handler(Looper.getMainLooper());

        width = image.getWidth() / 4;
        height = image.getHeight() / 3;
        image.setPixel(width, height, getResources().getColor(R.color.white));
        press.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacks(updateImage);
                mHandler.postDelayed(updateImage, 1000);
            }
        });

    }


    private Runnable updateImage = new Runnable() {
        final Random random = new Random();
        public void run() {

            image.setPixel(width, height, getResources().getColor(R.color.white));
            int widthIncrement = random.nextInt(3) - 1;
            int heightIncrement = random.nextInt(3) - 1;
            height = height + heightIncrement;
            width = width + widthIncrement;
            mHandler.postDelayed(this, 100);
        }
    };

}

0 个答案:

没有答案