簡體   English   中英

使用UIDynamics和CMMotionManager的重力旋轉UIView

[英]Rotating an UIView using UIDynamics and gravity from CMMotionManager

我有一個UIView,它是一個用繩子掛在釘子上的相框。 我試圖圍繞其anchorPoint旋轉視圖,以使視圖的底部保持平坦(與地面平行),而與設備旋轉無關。 我正在嘗試通過使用CMMotionManager和UIDynamics來實現這一目標,但今天似乎無法正常工作。 這是一些代碼...

- (void)viewDidLoad
{
[super viewDidLoad];

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

CGRect pictureFrameBounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.view.bounds)/2.5f, CGRectGetHeight(self.view.bounds)/5);
UIView *pictureFrame = [[UIView alloc] initWithFrame:pictureFrameBounds];
[pictureFrame setBackgroundColor:[UIColor redColor]];
[self.view addSubview:pictureFrame];

self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[pictureFrame]];

self.collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[pictureFrame]];
[self.collisionBehavior setTranslatesReferenceBoundsIntoBoundary:YES];
[self.animator addBehavior:self.collisionBehavior];

CGPoint anchorPoint = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetHeight(self.view.bounds)/8);
self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:pictureFrame
                                                    offsetFromCenter:UIOffsetMake(0.0f, -CGRectGetHeight(pictureFrame.bounds)/2.5f)
                                                    attachedToAnchor:anchorPoint];
[self.attachmentBehavior setDamping:0];
[self.attachmentBehavior setLength:0];
[self.attachmentBehavior setFrequency:0];
[self.animator addBehavior:self.attachmentBehavior];

UIDynamicItemBehavior *itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[pictureFrame]];
[itemBehavior setAllowsRotation:YES];
[self.animator addBehavior:itemBehavior];

NSOperationQueue* motionQueue = [NSOperationQueue new];

 self.motionManager = [[CMMotionManager alloc] init];
[self.motionManager startDeviceMotionUpdatesToQueue:motionQueue
                                        withHandler:^(CMDeviceMotion *motion, NSError *error) {
                                           [self.gravityBehavior setGravityDirection:CGVectorMake(motion.gravity.x, motion.gravity.y)];
                                        }];
}

我已經嘗試將motion.gravity.x作為itemBehavior上的angularForce來驗證力是否正確返回,並且視圖旋轉了正確的方向,這一切似乎都很好。 這種方法的問題在於,由於施加了恆定的力,因此視圖繼續旋轉。 使用setGravityDirection:無需旋轉即可錨定視圖的結果。 一些幫助將不勝感激! 謝謝!

嘗試將NSOperationQueue更改為mainQueue。 這對我有幫助。

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
[self.gravityBehavior setGravityDirection:CGVectorMake(motion.gravity.x, -(motion.gravity.y))];
}];

希望這也對您有所幫助。

暫無
暫無

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

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