在下面的应用程序中,由于某种原因,屏幕总是闪烁,文本上方也有绘图伪影。有可能解决这个问题吗?我在 Nexus 7 设备上运行 Android 4.4.2。
package com.example.TestSurfaceView;
import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import java.util.Random;
import android.os.SystemClock;
import android.view.TextureView;
public class MyActivity extends Activity implements TextureView.SurfaceTextureListener, Runnable {
TextureView view_;
Thread thread_;
long prev_ = -1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view_ = new TextureView(this);
view_.setSurfaceTextureListener(this);
thread_ = new Thread(this);
setContentView(view_);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
public void run() {
while(true) {
Canvas canvas = view_.lockCanvas();
Paint myPaint = new Paint();
myPaint.setColor(Color.WHITE);
myPaint.setStrokeWidth(10);
canvas.drawRect(100, 100, 300, 300, myPaint);
Random random = new Random();
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
int w = canvas.getWidth();
int h = canvas.getHeight();
int x = random.nextInt(w-1);
int y = random.nextInt(h-1);
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
canvas.drawPoint(x, y, paint);
if(prev_ == -1)
prev_ = SystemClock.elapsedRealtime();
else {
long curr = SystemClock.elapsedRealtime();
long diff = curr-prev_;
Paint text = new Paint(Color.WHITE);
text.setTextSize(15);
canvas.drawText("FPS: " + String.valueOf(1000.0 / diff), 100, 100, text);
prev_ = curr;
}
view_.unlockCanvasAndPost(canvas);
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i2) {
thread_.start();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i2) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
//To change body of implemented methods use File | Settings | File Templates.
}
}