snippets
import RealityKit
struct PinnedEntityComponent: Component {
weak var pinnedto: Entity? = nil
let pinName: String
var transform: Transform = .identity
}
struct PinnedEntitySystem: System {
static let query: EntityQuery = .init(where: .has(PinnedEntityComponent.self))
init(scene: Scene) {
}
func update(context: SceneUpdateContext) {
let entities = context.entities(matching: Self.query, updatingSystemWhen: .rendering)
for entity in entities {
guard let comp = entity.components[PinnedEntityComponent.self] else {
continue
}
//if the entity we are pinned to is no longer available then remove
//the pinned object from the scene
guard let pinnedto = comp.pinnedto else {
entity.removeFromParent()
continue
}
guard let pin = pinnedto.pins[comp.pinName] else { continue }
//pin position and orientation can actually be nil so ! is dangerous here
entity.setPosition(
pin.position(relativeTo: nil)!
, relativeTo: nil)
entity.setOrientation(
pin.orientation(relativeTo: nil)! * comp.transform.rotation
, relativeTo: nil)
}
}
}
snippets
Choose a readable Text color automatically based on the background color.
import SwiftUI
extension Color {
func bestTextColor() -> Color {
guard let components = self.resolve(in: .init()).cgColor.components else { return .black}
guard components.count >= 3 else { return .black }
let red: CGFloat = components[safe: 0]
let green: CGFloat = components[safe: 1]
let blue: CGFloat = components[safe: 2]
// Relative luminance approximation for contrast decisions.
let luminance = (0.299 * red) + (0.587 * green) + (0.114 * blue)
return luminance > 0.6 ? .black : .white
}
}
extension Array<CGFloat> {
subscript(safe index: Int, default: CGFloat = 0) -> CGFloat {
guard self.count > index else { return `default` }
return self[index]
}
}
snippets
Convert a hex string like #faf1ea into a SwiftUI Color.
import SwiftUI
extension Color {
init?(hex: String) {
var cleaned = hex.trimmingCharacters(in: .whitespacesAndNewlines)
cleaned = cleaned.replacingOccurrences(of: "#", with: "")
guard cleaned.count == 6, let value = UInt64(cleaned, radix: 16) else {
return nil
}
let red = Double((value >> 16) & 0xFF) / 255.0
let green = Double((value >> 8) & 0xFF) / 255.0
let blue = Double(value & 0xFF) / 255.0
self = Color(.sRGB, red: red, green: green, blue: blue, opacity: 1.0)
}
}
let cardBackground = Color(hex: "#faf1ea")