Created
March 26, 2020 23:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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