【问题标题】:Applying a Scale AffineTransform to a UIView changes its center将 Scale AffineTransform 应用于 UIView 会更改其中心
【发布时间】:2023-03-22 09:11:01
【问题描述】:

当用户点击其超级视图时,我正在运行此代码以缩小 UIView。然而,当应用 CGAffineTransformScale() 时,它也会改变中心。这是预期的行为吗?

-(void) onTap:(UITapGestureRecognizer *)tap{


    [UIView animateWithDuration:1.2
                          delay:0
                        options:0
                     animations:^{
                         CGAffineTransform transform = self.icon.transform;
                         NSLog(@"Previous center: %@", NSStringFromCGPoint(self.icon.center));

                         self.icon.transform = CGAffineTransformScale(transform, 0.5, 0.5);

                         NSLog(@"Next center: %@", NSStringFromCGPoint(self.icon.center));
                     } completion:^(BOOL finished) {
                         //
                     }];


}

【问题讨论】:

  • 视图中心向左下移
  • 您介意在调用 animateWithDuration 之前和在 completion:^ 块中编辑代码以输出边界和中心吗?并添加实际的 NSLog 输出?我使用 MonoTouch,但没有看到这种行为。中心保持原位,视图围绕中心点缩放。

标签: cocoa-touch uiview core-animation cgaffinetransform cgaffinetransformscale


【解决方案1】:

我终于发现了怎么回事:自动布局正在重新定位子视图并更改中心。

【讨论】:

【解决方案2】:

我在 ViewController 中使用 ObjC 测试了这段代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Create a subview
    CGRect bounds = CGRectMake(10, 10, 100, 100);
    UIView* v = [[UIView alloc] initWithFrame: bounds];
    [v setBackgroundColor:[UIColor yellowColor]];
    [self.view addSubview:v];

    icon = v;
}

并在 viewDidAppear 中启动了一个动画:

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"Previous center: %@", NSStringFromCGPoint(self.icon.center));

    [UIView animateWithDuration:1.2 
          delay:1.0 
        options:0 
     animations:^{
         NSLog(@"Before center: %@", NSStringFromCGPoint(self.icon.center));

         CGAffineTransform transform = self.icon.transform;
         self.icon.transform = CGAffineTransformScale(transform, 0.5, 0.5);

         NSLog(@"After center: %@", NSStringFromCGPoint(self.icon.center));
     }
     completion:^(BOOL finished){
         // nothing
         NSLog(@"Completion center: %@", NSStringFromCGPoint(self.icon.center));
     }];        
}

而且每次调用的中心都是一样的(60,60):

2012-09-24 10:22:11.776 ScaleView[19611:f803] Previous center: {60, 60}
2012-09-24 10:22:11.778 ScaleView[19611:f803] Before center: {60, 60}
2012-09-24 10:22:11.779 ScaleView[19611:f803] After center: {60, 60}
2012-09-24 10:22:13.979 ScaleView[19611:f803] Completion center: {60, 60}

所以我会说不,这不是预期的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 2011-03-19
    • 1970-01-01
    • 2016-08-01
    • 2021-07-04
    相关资源
    最近更新 更多