我写了一个CGRect类的扩展。我添加了一个方法,可以通过一个因子来扩展CGRect。但是我不知道如何写它以便我可以实现像
这样的东西 let newFrame = view.frame.scale(by: 0.8)
并返回一个要设置为newFrame的CGRect。
到目前为止我尝试了什么..
func scale(_ input: CGRect, byFactor factor: CGFloat) -> CGRect {
let newCentre = input.centre
let newHeight = input.size.height * factor
let newWidth = input.size.width * factor
let newSize = CGSize(width: newWidth, height: newHeight)
let newRect = CGRect(centre: newCentre, size: newSize)
return newRect
}
感谢任何帮助。谢谢!
编辑:
var upperLeft: CGPoint { return CGPoint(x: minX, y: minY) }
var centre: CGPoint { return CGPoint(x: upperLeft.x + size.width/2, y: upperLeft.y + size.height/2) }
init(centre: CGPoint, size: CGSize) {
let upperLeft = CGPoint(x: centre.x-size.width/2, y: centre.y-size.height/2)
self.init(origin: upperLeft, size: size)
}
我在扩展程序中实现的内容
答案 0 :(得分:0)
类,结构或枚举的扩展中的接收者由self
extension CGRect {
func scale(byFactor factor: CGFloat) -> CGRect {
let newCentre = self.centre
let newHeight = self.height * factor // CGRect has width and height properties
let newWidth = self.width * factor
let newSize = CGSize(width: newWidth, height: newHeight)
let newRect = CGRect(centre: newCentre, size: newSize)
return newRect
}
}
PS:centre
的更简单实现是
var centre : CGPoint {
return CGPoint(x:CGRectGetMidX(self), y:CGRectGetMidY(self))
}
答案 1 :(得分:0)
将CGRect扩展为具有相同中心的缩放矩形:
extension CGRect {
mutating func scale(factor: CGFloat) {
let newHeight = self.size.height * factor
let newWidth = self.size.width * factor
let newX = self.origin.x + (self.height - newHeight) / 2
let newY = self.origin.y + (self.width - newWidth) / 2
self = CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
}
}
用法:
view.frame.scale(0.8)