在另一个操作过程中,我必须每秒处理一次位图的像素,并在ImageView
中显示结果。这是操纵位图和更新ImageView
的方法:使用UI线程更新ImageView的位图
private void overlay(Bitmap bitmap) {
int j = 70;
while (flag) {
//here I manipulate some pixels of bitmap that corresponds to "j"
//and save result in "tempBmp":
...
//update imageView:
iv1.setImageBitmap(tempBmp);
iv1.postInvalidate();
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// }
//update "j":
j = (j+1)%src.rows();
}
}
以上方法是从UI线程(onclick
事件按钮的)以这种方式被称为:
runOnUiThread(new Runnable() {
public void run() {
overlay(bmp);
}
});
当应用程序正在运行,也没有问题,应用程序崩溃或ANR,但ImageView
(iv1
)不会更新。我调试代码和位图的像素正在操作。我也取消了try/catch
区块的注释,但结果是一样的。
奇怪的是:当我评论块的开始和结束时,位图操作正确(一次,对于j = 70
)和ImageView
更新如预期!
更新问题:
对于意见和eshayne和Onik我的答案改像素操纵overlay
方法,简单的操作和检查结果,但结果是一样的。真正overlay
方法使用openCV
但在这里,我改变像素的颜色,所以你可以看到的结果,而不使用openCV
:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread(new Runnable() {
@Override
public void run() {
overlay(bmp);
}
}).run();
}
});
叠加法,简化:
private void overlay(Bitmap bitmap){
int j = 0;
tempBmp = Bitmap.createBitmap(bitmap);
while (j < bitmap.getHeight()) {
for (int i = 0; i < bitmap.getWidth(); i++) {
tempBmp.setPixel(i, j, 0);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// post the changes to Ui thread
iv1.post(new Runnable() {
@Override
public void run() {
iv1.setImageBitmap(tempBmp);
}
});
j = (j + 1);
}
}
如何更新ImageView
,每第二个是while
?我做错了什么?
我看不到任何线程,但主线程 – Blackbelt 2014-10-03 18:57:15
@blackbelt行!但为什么imageview不更新? – hasanghaforian 2014-10-03 18:58:50
我看不到你在修改位图的位置 – Blackbelt 2014-10-03 19:01:25