Skip to content

Instantly share code, notes, and snippets.

@ecoopnet
Created February 14, 2019 05:09
Show Gist options
  • Save ecoopnet/8638cc8d4bd9d3f8e4db1326da30fc8f to your computer and use it in GitHub Desktop.
Save ecoopnet/8638cc8d4bd9d3f8e4db1326da30fc8f to your computer and use it in GitHub Desktop.
import Foundation
extension CGPoint {
// CGPoint -> Point<Double> に変換
func toPoint() -> Point<Double> {
return Point<Double>(x: Double(x), y: Double(y))
}
}
extension CGSize {
// CGSize -> Size<Double> に変換
func toSize() -> Size<Double> {
return Size<Double>(width: Double(width), height: Double(height))
}
}
extension CGRect {
// CGRect -> Size<Double> に変換
func toRect() -> Rect<Double> {
return Rect<Double>(origin: origin.toPoint(), size: size.toSize())
}
}
extension Quadrilateral {
// 外接矩形(circumscribed rectangle)を得る
func toRect() -> Rect<Double> {
let xList = [
Double(topLeft.x), Double(topRight.x),
Double(bottomLeft.x), Double(bottomRight.x)]
let yList = [
Double(topLeft.y), Double(topRight.y),
Double(bottomLeft.y), Double(bottomRight.y)]
let origin = Point<Double>(x: xList.min()!, y: yList.min()!)
let size = Size<Double>(
width: xList.max()! - origin.x,
height: yList.max()! - origin.y)
return Rect<Double>(origin: origin, size: size)
}
}
// 2次元座標系のモノを表すのに使えるドメインモデル
// CGPoint, CGSize, CGRect などに互換
import Foundation
/// 2次元座標上の1点を表すモデル
struct Point<T: Numeric> {
let x: T
let y: T
}
/// 2次元のサイズを表すモデル
struct Size<T: Numeric> {
/// 幅
let width: T
/// 高さ
let height: T
}
// 2次元の矩形を表すモデル
struct Rect<T: Numeric> {
/// 矩形の起点(左上の座標)
let origin: Point<T>
/// 矩形のサイズ
let size: Size<T>
/// 左端のX
var left: T { return origin.x }
/// 右端のX
var right: T { return origin.x + size.width }
/// 上端のY
var top: T { return origin.y }
/// 下端のY
var bottom: T { return origin.y + size.height }
/// 左上の座標
var topLeft: Point<T> { return origin }
/// 右下の座標
var bottomRight: Point<T> { return Point( x: right, y: bottom) }
/// 右上の座標
var topRight: Point<T> { return Point(x: right, y: top) }
/// 左下の座標
var bottomLeft: Point<T> { return Point(x: left, y: bottom) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment