2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自分しか得しなさそうなCGRectを作るextensionまとめ

#1.二つのCGPointから作る

CGRect+doublePoints
extension CGRect {
    init(point1: CGPoint, point2: CGPoint) {
        self.init(x: min(point1.x, point2.x),
                  y: min(point1.y, point2.y),
                  width: fabs(point1.x - point2.x),
                  height: fabs(point1.y - point2.y))
    }
}
使用例
let rect = CGRect(point1: CGPoint(x: 50, y: 20), point2: CGPoint(x: 10, y: 100))
// (x: 10.0, y: 20.0, width: 40.0, height: 80.0)

##使い所
パンジェスチャーの開始地点と終了地点とかでCGRectを用意する時とかに使える。

#2.中心のCGPoint+CGSizeから作る

CGRect+center
extension CGRect {
    init(center: CGPoint, size: CGSize) {
        self.init(x: center.x - size.width/2,
                  y: center.y - size.height/2,
                  width: size.width,
                  height: size.height)
    }
}
使用例
let rect1 = CGRect(center: CGPoint(x: 200, y: 100), size: CGSize(width: 20, height: 100))
// (x: 190.0,y: 50.0,width: 20.0,height: 100.0)

##使い所
UIViewの中心にaddSubviewとかしたい時に使う。

#3.右下CGPoint+CGSizeから作る

CGRect+bottomRight
extension CGRect {
	init(bottomRight: CGPoint, size: CGSize) {
        self.init(x: bottomRight.x - size.width,
                  y: bottomRight.y - size.height,
                  width: size.width,
                  height: size.height)
    }
}
使用例
let rect = CGRect(bottomRight: CGPoint(x: 100, y: 200), size: CGSize(width: 50, height: 30))
// (x: 50.0,y: 170.0,width: 50.0,height 30.0)

##使い所
ごく稀に右下基準でViewを置きたい時に使うけど、本当に稀。

#4.CGRectをX倍した新たなCGRectを作る

CGRect+scale
extension CGRect {
    init(baseRect: CGRect, scale: CGFloat) {
        self.init(x: baseRect.origin.x,
                  y: baseRect.origin.y,
                  width: baseRect.width * scale,
                  height: baseRect.height * scale)
    }
}
使用例
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let rect2 = CGRect(baseRect: rect, scale: 1.5)
// (x: 0.0,y: 0.0,width: 150.0,height: 150.0)

##使い所
これ使うくらいなら、演算子作った方がいいかもって感じ。

#続く?
変わったCGRectを作る機会があれば書く。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?