使用CGAffineTransform缩放并设置锚点

时间:2012-01-06 12:11:01

标签: iphone ios scaling cgaffinetransform

如果我理解正确缩放UIViewCGAffineTransform将转换定位到其中心。

特别是:

self.frame = CGRectMake(0,0,100,100);
self.transform = CGAffineTransformMakeScale(2, 2);
NSLog(@"%f;%f;%f;%f", self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height); 

打印:

-50;-50;200;200

如何创建使用特定锚点(例如0; 0)的CGAffineTransform比例?

3 个答案:

答案 0 :(得分:67)

(a)中

缩放然后翻译?

类似的东西:

CGAffineTransform t = CGAffineTransformMakeScale(2, 2);
t = CGAffineTransformTranslate(t, width/2, height/2);
self.transform = t;

(b)中

设置锚点(这可能是你想要的)

[self layer].anchorPoint = CGPointMake(0.0f, 0.0f);
self.transform = CGAffineTransformMakeScale(2, 2);

(c)中

再次设置中心以确保它在同一个地方?

CGPoint center = self.center;
self.transform = CGAffineTransformMakeScale(2, 2);
self.center = center;

答案 1 :(得分:4)

首先#import <QuartzCore/QuartzCore.h>然后设置视图的锚点:

   [[self layer] setAnchorPoint:CGPointMake(0, 0)];

答案 2 :(得分:0)

这是我在 Swift5

中将视图的比例保持在原点 (0,0) 的同时找到视图的方式
func animate() {
    myView.setAnchorPoint(CGPoint(x: 0, y: 0))
    myView.transform = CGAffineTransform(translationX: -0.5, y: -0.5)
    let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeOut) {
        self.myView.transform = CGAffineTransform(scaleX: 0.25, y: 0.25)
    }
}

extension UIView {
func setAnchorPoint(_ point: CGPoint) {
    var newPoint = CGPoint(x: bounds.size.width * point.x, y: bounds.size.height * point.y)
    var oldPoint = CGPoint(x: bounds.size.width * layer.anchorPoint.x, y: bounds.size.height * layer.anchorPoint.y);

    newPoint = newPoint.applying(transform)
    oldPoint = oldPoint.applying(transform)

    var position = layer.position

    position.x -= oldPoint.x
    position.x += newPoint.x

    position.y -= oldPoint.y
    position.y += newPoint.y

    layer.position = position
    layer.anchorPoint = point
}
}

归功于Hacking with Swift