Skip to content

Instantly share code, notes, and snippets.

@HonmaMasaru
Last active April 23, 2023 22:32
Show Gist options
  • Save HonmaMasaru/eacbfae59458534145bf79875b2fae47 to your computer and use it in GitHub Desktop.
Save HonmaMasaru/eacbfae59458534145bf79875b2fae47 to your computer and use it in GitHub Desktop.
import SwiftUI
import CoreMotion
import PlaygroundSupport
struct ContentView: View {
/// モーションマネージャー
private let motionManager: CMMotionManager = .init()
/// 角度
@State var angle: Angle = .init()
/// Body
var body: some View {
ZStack {
Circle()
.fill(AngularGradient(gradient: .init(colors: [.gray, .black, .gray]), center: .center, angle: angle))
}
.frame(width: 300, height: 300)
.onAppear {
if motionManager.isDeviceMotionAvailable {
motionManager.startDeviceMotionUpdates(to: .current!) { motion, _ in
guard let motion else { return }
angle = get(angle: motion.attitude)
}
}
}
}
/// スクリーンの傾き角度を検出
/// - Parameter attitude: 姿勢
/// - Returns: 傾き角度
private func get(angle attitude: CMAttitude) -> Angle {
var pitch = attitude.pitch
var roll = attitude.roll
// pitchとrollの値をデバイスの向きに基づいて変換する
switch UIDevice.current.orientation {
case .portraitUpsideDown:
pitch = -pitch
roll = -roll
case .landscapeLeft:
let tmp = pitch
pitch = -roll
roll = tmp
case .landscapeRight:
let tmp = pitch
pitch = roll
roll = -tmp
default:
break
}
return .radians(atan2(pitch, roll))
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.setLiveView(ContentView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment