Skip to content

Instantly share code, notes, and snippets.

@miff
Created March 26, 2020 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miff/6e57c3e94d13ada415af5e2b1545e653 to your computer and use it in GitHub Desktop.
Save miff/6e57c3e94d13ada415af5e2b1545e653 to your computer and use it in GitHub Desktop.
Depends on orientation of the device, calculate a safe area and creates a rectangle with coordinates and dimensions.
//
// SKScene+extension.swift
//
// Created by Milan miff Djordjevic on 2/20/19.
// Copyright © 2020 miff.me. All rights reserved.
//
import SpriteKit
extension SKScene {
/// Returns a CGRect of a safe area
///
/// Depends on orientation of the device,
/// calculate a safe area and
/// creates a rectangle with coordinates and dimensions based on calculation
/// specified as floating-point values.
///
var safeArea: CGRect {
get {
if UIApplication.shared.statusBarOrientation.isPortrait {
let ratio: CGFloat = UIScreen.main.bounds.height / UIScreen.main.bounds.width
let safeWidth = size.height / ratio
let safeMargin = (size.width - safeWidth) / 2
return CGRect(x: safeMargin, y: 0, width: safeWidth, height: size.height)
} else {
let ratio: CGFloat = UIScreen.main.bounds.width / UIScreen.main.bounds.height
let safeHeight = size.width / ratio
let safeMargin = (size.height - safeHeight) / 2
return CGRect(x: 0, y: safeMargin, width: size.width, height: safeHeight)
}
}
set { }
}
/// Draw a DEBUG safe area
///
/// - Parameters: none
func debugSafeArea() {
let shape = SKShapeNode(rect: safeArea)
shape.strokeColor = SKColor.red
shape.lineWidth = 4
addChild(shape)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment