вращать UIImageView вокруг произвольной точки - PullRequest
1 голос
/ 29 июля 2011

У меня есть UIImageView, который я вращаю вокруг его центра:

imageHorizon.layer.anchorPoint = CGPointMake(0.5, 0.5);
imageHorizon.transform = CGAffineTransformRotate(imageHorizon.transform, angleToRotate*(CGFloat)(M_PI/180));

Иногда я также перемещаю это изображение влево или вправо, а затем поворачиваю снова. Я бы хотел, чтобы центр вращения постоянно находился в одной и той же точке (которая фактически является центром суперпредставления) Как я могу это сделать?

ура

Ответы [ 4 ]

5 голосов
/ 27 марта 2012
self.imgView.layer.anchorPoint = CGPointMake(0.0,1.0);
self.imgView.layer.position = CGPointMake(100,200.0);
CGAffineTransform cgaRotateHr = CGAffineTransformMakeRotation(-(3.141/4));
[self.imgView setTransform:cgaRotateHr];
3 голосов
/ 05 июня 2013

Это старый вопрос, но другие решения у меня не сработали, поэтому я нашел другое решение:

Поворот изображения - это, по сути, обычное вращение с примененным переводом, гарантирующим, что точка, вокруг которой вы хотите повернуть, все еще остается в том же месте после поворота. Чтобы сделать это, рассчитайте позицию CGPoint в вашем изображении до поворота, получите положение после поворота и примените разницу в качестве перевода к изображению, «привязав» его к правильному положению. Вот код, который я использовал:

Имейте в виду, что перевод должен применяться с помощью CGAffineTransform, а не перемещения .center, потому что перевод должен быть относительно поворота, и CGAffineTransformTranslate () позаботится об этом.

// Note: self is the superview of _imageView

// Get the rotation point
CGPoint rotationPointInSelf = self.center; // or whatever point you want to rotate around
CGPoint rotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self];

// Rotate the image
_imageView.transform = CGAffineTransformRotate(_imageView.transform, angle);

// Get the new location of the rotation point
CGPoint newRotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self];

// Calculate the difference between the point's old position and its new one
CGPoint translation = CGPointMake(rotationPointInImage.x - newRotationPointInImage.x, rotationPointInImage.y - newRotationPointInImage.y);

// Move the image so the point is back in it's old location
_imageView.transform = CGAffineTransformTranslate(_imageView.transform, -translation.x, -translation.y);
1 голос
/ 29 июля 2011

Вы можете сделать изображение подпредставлением другого вида, а затем повернуть суперпредставление, чтобы получить этот эффект. Другой подход заключается в установке свойства anchorPoint, как описано в документах .

0 голосов
/ 28 мая 2014

Я использую этот код для поворота вокруг точки (0,0).Может быть, это поможет вам понять, как активировать то, что вы хотите.

    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;

    CGRect frame_smallView = CGRectMake(-width, -height, width, height);
    UIView *smallView = [[UIView alloc] initWithFrame:frame_smallView];
    smallView.backgroundColor = darkGrayColor;

    // Select x and y between 0.0-1.0. 
    // The default is (0.5f,0.5f) that is the center of the layer
    // (1.0f,1.0f) is the right bottom corner
    smallView.layer.anchorPoint = CGPointMake(1.0f, 1.0f);

    // Rotate around this point
    smallView.layer.position = CGPointMake(0, 0);

    [self.view insertSubview:smallView belowSubview:self.navBar];

    [UIView animateWithDuration:1
                     animations:^{
                         smallView.transform = CGAffineTransformMakeRotation(M_PI);
                     }
                     completion:^(BOOL finished){
                         [self.navigationController popViewControllerAnimated:NO];
                     }];
...