安卓 View 和传感器

标签 android view sensors

我有一个使用方向传感器的罗盘应用程序,每次传感器改变时,我的罗盘 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/

相关文章:

android - 如何在不使用渲染脚本的情况下模糊图像的特定部分,因为我的 minsdk 是 14。

android - 我如何查看从 http post 调用返回的 json?

android - 在页面android中显示CoordinatorLayout

javascript - angularjs:检查 View 中的值

objective-c - Objective-C 有观点吗?

Android - 加速下降(粉碎)

android - 如何将状态和调整与 window.setSoftInputMode() 结合起来

iphone - 如何布局可滚动的 iPhone View

mysql - 适用于传感器数据的数据存储

android - 传感器和 min3d ANDROID