Scale UIView with the top center as the anchor point?

前端 未结 3 1116
情话喂你
情话喂你 2020-12-23 22:43

I\'m scaling a UIView with CGAffineTransformMakeScale but I want to keep it anchored to it\'s current top center point as it\'s scaled.

I\'ve looked into setting

3条回答
  •  佛祖请我去吃肉
    2020-12-23 23:07

    By using an extension

    Scaling an UIView with a specific anchor point while avoiding misplacement:

    extension UIView {
        func applyTransform(withScale scale: CGFloat, anchorPoint: CGPoint) {
            layer.anchorPoint = anchorPoint
            let scale = scale != 0 ? scale : CGFloat.leastNonzeroMagnitude
            let xPadding = 1/scale * (anchorPoint.x - 0.5)*bounds.width
            let yPadding = 1/scale * (anchorPoint.y - 0.5)*bounds.height
            transform = CGAffineTransform(scaleX: scale, y: scale).translatedBy(x: xPadding, y: yPadding)
        }
    }
    

    So to shrink a view to half of its size with its top center as anchor point:

    view.applyTransform(withScale: 0.5, anchorPoint: CGPoint(x: 0.5, y: 0))
    

提交回复
热议问题