CanvaCompass is a demo Android application showcasing how to implement a compass UI using Canvas API in both traditional XML Views and modern Jetpack Compose.
- Dual UI Implementation:
- Traditional
CompassView(extendingView). - Modern
CompassScreen(usingJetpack Compose).
- Traditional
- Sensor Integration: Uses
Rotation Vector Sensorfor high precision or a combination of Accelerometer and Magnetometer as a fallback. - Orientation Support: Automatically adjusts azimuth calculation based on screen rotation (Portrait/Landscape).
- Smooth Animations: Fluid needle rotation using
ValueAnimator(View) andanimateFloatAsState(Compose).
The app determines the heading using the following logic:
- Sensor Data Collection: The app prioritizes
Sensor.TYPE_ROTATION_VECTOR. If unavailable, it falls back toSensor.TYPE_ACCELEROMETERandSensor.TYPE_MAGNETIC_FIELD. - Rotation Matrix: A rotation matrix is calculated using
SensorManager.getRotationMatrix(or from the rotation vector) to determine device orientation relative to the Earth. - Coordinate Remapping: To ensure the compass works correctly in landscape mode, the coordinate system is remapped using
SensorManager.remapCoordinateSystembased on the current display rotation (Surface.ROTATION_X). - Orientation Angles:
SensorManager.getOrientationconverts the matrix into orientation angles (azimuth, pitch, and roll). - Normalization: The azimuth value is converted from radians to degrees and normalized to a [0, 360) range.
#Android #Kotlin #JetpackCompose #Canvas #CustomView #Compass #Sensors #RotationVector #Magnetometer #UI #MobileDevelopment
P.S. A performance metrics comparison between the View and Compose implementations is planned to be added later.
