簡體   English   中英

核心動畫圍繞點旋轉

[英]Core Animation rotation around point

我想讓IBOutlet圍繞父視圖中的特定點旋轉,目前我只知道如何圍繞錨點旋轉它,但是,我想使用對象層外的一個點。

相對於從該點前進的設備計算旋轉角度。

- (void)viewDidLoad{
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.headingFilter = 1;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
[locationManager startUpdatingLocation];
compassImage.layer.anchorPoint=CGPointZero;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
    // Convert Degree to Radian and move the needle
    float oldRad =  -manager.heading.trueHeading * M_PI / 180.0f;
    float newRad =  -newHeading.trueHeading * M_PI / 180.0f;        
    CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    theAnimation.fromValue = [NSNumber numberWithFloat:oldRad];
    theAnimation.toValue=[NSNumber numberWithFloat:newRad];
    theAnimation.duration = 0.5f;
    [compassImage.layer addAnimation:theAnimation forKey:@"animateMyRotation"];
    compassImage.transform = CGAffineTransformMakeRotation(newRad);

    NSLog(@"%f (%f) => %f (%f)", manager.heading.trueHeading, oldRad, newHeading.trueHeading, newRad);

  }

我如何通過alpha旋轉UIImageView(x,y)?

對於圍繞特定點(內部或外部)旋轉,您可以更改圖層的錨點,然后應用類似於我在此博客文章中所寫的常規旋轉變換動畫。

您只需要知道錨點也會影響圖層在屏幕上的顯示位置。 更改定位點時,還必須更改位置以使圖層顯示在屏幕上的相同位置。

假設圖層已經放置在它的起始位置並且周圍的旋轉點已知,則可以像這樣計算錨點和位置(注意錨點位於圖層邊界的單位坐標空間中(意思是x和y在范圍內的范圍從0到1)):

CGPoint rotationPoint = // The point we are rotating around

CGFloat minX   = CGRectGetMinX(view.frame);
CGFloat minY   = CGRectGetMinY(view.frame);
CGFloat width  = CGRectGetWidth(view.frame);
CGFloat height = CGRectGetHeight(view.frame);

CGPoint anchorPoint =  CGPointMake((rotationPoint.x-minX)/width,
                                   (rotationPoint.y-minY)/height);

view.layer.anchorPoint = anchorPoint;
view.layer.position = rotationPoint; 

然后,您只需對其應用旋轉動畫,例如:

CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotate.toValue = @(-M_PI_2); // The angle we are rotating to
rotate.duration = 1.0;

[view.layer addAnimation:rotate forKey:@"myRotationAnimation"];

請注意,您已更改了錨點,因此position不再位於frame的中心,如果應用其他變換(例如比例),它們也將相對於錨點。

翻譯大衛對swift 3的回答:

    let rotationPoint = CGPoint(x: layer.frame.width / 2.0, y: layer.frame.height / 2.0) // The point we are rotating around

    print(rotationPoint.debugDescription)
    let width = layer.frame.width
    let height = layer.frame.height
    let minX = layer.frame.minX
    let minY = layer.frame.minY

    let anchorPoint = CGPoint(x: (rotationPoint.x-minX)/width,
                              y: (rotationPoint.y-minY)/height)

    layer.anchorPoint = anchorPoint;
    layer.position = rotationPoint;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM