我有一个使用方向传感器的罗盘应用程序,每次传感器改变时,我的罗盘 View 都会失效,以便向北旋转。我的指南针是一个 444px x 444px 位图。我面临的问题是,每当传感器发生变化并且您看到罗盘旋转时它就会滞后,基本上是 fps 差。我尝试改用表面 View 并更改 SENSOR_DELAY,但没有任何更改。如果有人能帮我找出这个问题的答案,我会很高兴。
注册传感器
orientation = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_UI);
每当传感器发生变化
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (compass != null) {
float[] v = event.values;
north = v[0];
compass.setNorth(-north);
}
}
指南针 View 中的方法
public void setNorth(float n) {
north_changed = true;
north = n;
invalidate();
}
private void drawBackground(Canvas canvas) {
canvas.save();
if (north_changed == true) {
canvas.rotate(north);
}
float maxwidth = (float) (backgroundTexture.getWidth() * Math.sqrt(2));
float maxheight = (float) (backgroundTexture.getHeight() * Math.sqrt(2));
float ratio = Math.min(w / maxwidth, h / maxheight);
int width = (int) (backgroundTexture.getWidth() * ratio);
int height = (int) (backgroundTexture.getHeight() * ratio);
canvas.drawBitmap(
backgroundTexture,
new Rect(0, 0, backgroundTexture.getWidth(), backgroundTexture
.getHeight()), new RectF(-width / 1.5f, -height / 1.5f,
width / 1.5f, height / 1.5f), facePaint);
canvas.restore();
}
绘制
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (showCompass) {
w = getWidth();
h = getHeight();
cx = w / 2;
cy = h / 2;
canvas.translate(cx, cy);
loadImages();
drawBackground(canvas);
}
}
最佳答案
你可以试试这个
替换:
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_UI);
用这个:
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_FASTEST);
如果你想要一些额外的平滑度
替换:
if (compass != null) {
float[] v = event.values;
north = v[0];
compass.setNorth(-north);
}
用这个:
if (compass != null) {
float[] v = event.values;
north =north*0.1f + v[0]*0.9f;
compass.setNorth(-north);
}
关于安卓 View 和传感器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127675/