用于传感器值俯仰和滚动的更高级别 API



我正在实现自己的相机活动。要旋转捕获的图像,我需要知道拍摄时的方向。传感器值俯仰和滚动是否有更高级别的 API,告诉我我的设备面向:

自上而下 - 保持手机正常,纵向
下顶
左右 - 横向 手机顶部位于右侧
左右 - 横向 手机顶部位于左侧

或者有没有其他方法可以直接从系统中获取它?

可悲的是,当相机不处于横向模式时,相机在Android上以奇怪的方式工作(这是Android上相机的"自然"方向)。

最好的办法是将活动设置为横向模式,并添加onConfigurationChanged事件(并将android:configChanges="orientation"添加到清单中)以获取当前方向。

捕获图像时,请检查方向并根据您希望的任何逻辑进行操作。

Ok在一定程度上

解决了我的问题,因此它对我有用,我省略了向下识别。

public class DeviceOrientation {
public static final int ORIENTATION_PORTRAIT = 0;
public static final int ORIENTATION_LANDSCAPE_REVERSE = 1;
public static final int ORIENTATION_LANDSCAPE = 2;
public static final int ORIENTATION_PORTRAIT_REVERSE = 3;
int smoothness = 1;
public float averagePitch = 0;
public float averageRoll = 0;
public int orientation = ORIENTATION_PORTRAIT;
private float[] pitches;
private float[] rolls;
public DeviceOrientation(int smoothness) {
    this.smoothness = smoothness;
    pitches = new float[smoothness];
    rolls = new float[smoothness];
}
public void addSensorEvent(SensorEvent event) {
    azimuth = event.values[0];
    averagePitch = addValue(event.values[1], pitches);
    averageRoll = addValue(event.values[2], rolls);
    orientation = calculateOrientation();
}
private float addValue(float value, float[] values) {
    float average = 0;
    for(int i=1; i<smoothness; i++) {
        values[i-1] = values[i];
        average += values[i];
    }
    values[smoothness-1] = value;
    average = (average + value)/smoothness;
    return average;
}
/** handles all 4 possible positions perfectly */
private int calculateOrientation() {
    // finding local orientation dip
    if (((orientation == ORIENTATION_PORTRAIT || orientation == ORIENTATION_PORTRAIT_REVERSE)
            && (averageRoll > -30 && averageRoll < 30))) {
        if (averagePitch > 0)
            return ORIENTATION_PORTRAIT_REVERSE;
        else
            return ORIENTATION_PORTRAIT;
    } else {
        // divides between all orientations
        if (Math.abs(averagePitch) >= 30) {
            if (averagePitch > 0)
                return ORIENTATION_PORTRAIT_REVERSE;
            else
                return ORIENTATION_PORTRAIT;
        } else {
                if (averageRoll > 0) {
                    return ORIENTATION_LANDSCAPE_REVERSE;
                } else {
                    return ORIENTATION_LANDSCAPE;
                }
        }
    }
}

解释:如果我处于纵向模式并向前倾斜移动直到它处于水平位置,它将由于代码的其余部分而切换到横向。因此,我检查它是否是纵向的,并使条件难以翻阅此模式。这就是我对当地浸泡的看法。其余的只是分为所有 3 个方向。

有一件事是不好的。如果设备处于landscape_x状态并向后倾斜几度,则皮奇从 ~2 跳到 ~175。此时,我的代码正在横向和纵向之间切换。

平滑度将通过组合最后 n 个值并计算平均值来平滑传感器数据的值。真的没有必要。

我希望这将帮助其他人。如果您可以进一步改进代码,请告诉我。

最新更新