是否旋转自定义视图



我在自定义视图上有一些绘图,想让用户旋转

viewContorller.m:

-(void)setMyView:(myView *)myView {
...
    [self.faceView addGestureRecognizer:[[UIRotationGestureRecognizer alloc] initWithTarget:faceView action:@selector(rotate:)]];
...
}

faceView.m

- (void)rotate:(UIRotationGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateChanged) {
        self.transform = CGAffineTransformMakeRotation(gesture.rotation);
        gesture.rotation = 0;
    }
}

它只是不起作用,但很摇晃?

使用以下代码,并在viewController.h类中添加UIGestureRecognizerDelegate。

-(void)setMyView:(myView *)myView {
//...
        UIRotationGestureRecognizer* rotateRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
        rotateRecognizer.delegate = self;
        [self.faceView addGestureRecognizer:rotateRecognizer];
//...
}

我认为这将对你有所帮助。

好的,问题出在你的rotate方法上,试试这个代码,

- (void)rotate:(UIRotationGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateChanged) {
        self.transform = CGAffineTransformRotate(self.transform, [gesture rotation]);
        gesture.rotation = 0;
    }
}

使用此代码旋转视图,在视图上启用用户交互和多点触摸功能。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    [self.myview addGestureRecognizer:rotationGesture];
}
- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
        [gestureRecognizer setRotation:0];
    }
}
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        UIView *piece = gestureRecognizer.view;
        CGPoint locationInView = [gestureRecognizer locationInView:piece];
        CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];
        piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
        piece.center = locationInSuperview;
    }
}

此代码来自apples示例代码触摸。

最新更新