[英]Rotating a wheel?
我在這里閱讀了一些有關此的示例,但無法使其正常工作。 我有一些名為Wheel的UIView,我想在其中觸摸和拖動時進行旋轉。 它應該像一個真正的輪子一樣工作,因此,如果我在某個點觸摸,它將不會旋轉到那個點,只有當我拖動手指時,我才會旋轉。
我試過了,但是我做的每一個小動作都會使我完全旋轉。 我想將天使添加到視圖中,而不是將其添加到新天使中。
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self];
CGPoint center=wheel.center;
float xLeg = fabs(center.x - touchPoint.x);
float yLeg = fabs(center.y-touchPoint.y);
float angle = atan(xLeg / yLeg);
NSLog(@"%f",angle);
wheel.transform = CGAffineTransformMakeRotation( angleInDegree );
}
這應該可以解決問題。 請注意,我如何將第一個接觸點存儲在touchesBegan:withEvent:
。 這使我可以從拖動時獲得的每個觸摸點中減去第一個觸摸點,從而獲得需要旋轉的真實角度。
編輯
我已經進行了一些調整,以便即使經過幾次觸摸也可以保持平滑和規則。
演示
WheelViewController.m
@interface WheelViewController () {
CGPoint startPoint;
CGFloat startAngle;
CGFloat endAngle;
}
@end
@implementation WheelViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
startPoint = [touch locationInView:self.view];
startAngle = [self angleForTouchPoint:startPoint] - endAngle;
NSLog(@"\r\nStart angle: %f", startAngle);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGFloat touchAngle = [self angleForTouchPoint:touchPoint];
NSLog(@"Touch angle: %f", touchAngle);
self.wheel.transform = CGAffineTransformMakeRotation(fmodf(touchAngle - startAngle, 2 * M_PI));
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
endAngle = [self angleForTouchPoint:touchPoint] - startAngle;
NSLog(@"End angle: %f", endAngle);
}
- (CGFloat)angleForTouchPoint:(CGPoint)touchPoint {
CGPoint center = self.wheel.center;
float xLeg = touchPoint.x - center.x;
float yLeg = touchPoint.y - center.y;
float angle = fmodf(atan(yLeg/xLeg), (2 * M_PI));
if (xLeg < 0) {
angle += M_PI;
}
return angle;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.