[英]Android: Error while using bitmap to display image using android studio
[英]how to hold the image on screen while using bitmap android
我必須使用位圖顯示三個圖像(dex5,dex6,dex7)。 當我運行以下代碼時,圖像會在屏幕上顯示幾毫秒,並且此過程不會結束。 首先,如何保持每個圖像更長的時間(例如1秒鍾)? 其次,我要繼續整個過程(每幅圖像顯示1秒鍾)30秒。 如何根據時間停止此過程???
我的代碼是:
public class DrawingTheImage extends View{
private Bitmap[] btm = new Bitmap[3];
int x , y;
Random rand = new Random();
int i;
public DrawingTheImage(Context context) {
super(context);
// TODO Auto-generated constructor stub
btm[0] = BitmapFactory.decodeResource(getResources(), R.drawable.dex5);
btm[1] = BitmapFactory.decodeResource(getResources(), R.drawable.dex6);
btm[2] = BitmapFactory.decodeResource(getResources(), R.drawable.dex7);
x = 0;
y = 250;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Random rand = new Random();
int i;
boolean j;
i = rand.nextInt(3);
if (j = rand.nextBoolean()){
canvas.drawBitmap(btm[i], 100, y, null);
}else if (j = rand.nextBoolean()) {
canvas.drawBitmap(btm[i], 200, y, null);
}else if(j = rand.nextBoolean()){
canvas.drawBitmap(btm[i], 300, y, null);
}
invalidate();
}
}
一秒鍾多次調用onDraw,我不知道多久一次。 那是您看到閃爍的一半原因。 另一半是你的代碼
int i;
boolean j;
i = rand.nextInt(3);
if (j = rand.nextBoolean()){
canvas.drawBitmap(btm[i], 100, y, null);
}else if (j = rand.nextBoolean()) {
canvas.drawBitmap(btm[i], 200, y, null);
}else if(j = rand.nextBoolean()){
canvas.drawBitmap(btm[i], 300, y, null);
}
這條線
j = rand.nextBoolean()
您有一個if條件條件為3的if else if語句,這意味着第一個語句將執行,否則將不執行。
要完成您想完成的任務,您需要某種計時器,並且僅在計時器到期后才更改圖像。
long timer = 0;
long delay = 30000;
Bitmap image = null;
public void changeImage(){
if(delay < 0){
//change image
int i = rand.nextInt(3);
image = btm[i];
delay = 30000;
}else{
delay -= (System.currentTimeMillis() - timer);
}
timer = System.currentTimeMillis();
}
然后在您的onDraw方法中,您只需要
changeImage();
canvas.drawBitmap(image,x,y,null);
原因實際上是在onDraw方法中調用了invalidate()
。 調用invalidate將導致新的繪圖傳遞,這將導致對onDraw本身的新調用。 因此,您陷入了無盡的onDraw遞歸中。 您需要刪除此invalidate()
。 也不要在onDraw
方法中創建新對象。 正如triggs指出的那樣,即使沒有無限遞歸,也會多次調用onDraw,因此您應該不惜一切代價避免在那里創建對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.