How can I increase the size of a CGRect by a certain percent value?

后端 未结 7 2012
春和景丽
春和景丽 2021-02-12 14:22

How can I increase the size of a CGRect by a certain percent value? Should I use some form of CGRectInset to do it?

Example:

Assume I have a CGRect:

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 14:51

    Using Swift you can retain the center point (relative to the source Rect) and increase/decrease the size as follows using an extension:

    extension CGRect {
        func centerAndAdjustPercentage(percentage p: CGFloat) -> CGRect {
            let x = self.origin.x
            let y = self.origin.y
            let w = self.width
            let h = self.height
    
            let newW = w * p
            let newH = h * p
            let newX = (w - newW) / 2
            let newY = (h - newH) / 2
    
            return CGRect(x: newX, y: newY, width: newW, height: newH)
        }
    }
    let newRect = oldRect.centerAndAdjustPercentage(percentage: 0.25)
    

提交回复
热议问题