//弧度转角度
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
//角度转弧度
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
CALayer *needleLayer = [CALayer layer];
// 设置锚点
needleLayer.anchorPoint = CGPointMake(0.5, 1);
// 锚点位置
needleLayer.position = CGPointMake(105, 300);
// bounds
needleLayer.bounds = CGRectMake(100, 100, 10, 200);
// 添加图片
needleLayer.contents = (id)[UIImage imageNamed:@"zhizhen"].CGImage;
[self.view.layer addSublayer:needleLayer];
needleLayer.transform = CATransform3DMakeRotation(self.currentRadian, 0, 0, 1);
_needleLayer = needleLayer;
[self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]];
- (void)handlePan:(UIGestureRecognizer *)gesture {
CGPoint currentPosition = [gesture locationInView:self.view];
if (gesture.state == UIGestureRecognizerStateBegan)
{
// NSLog(@"[%f, %f]", currentPosition.x, currentPosition.y);
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
NSLog(@"0000000000000000000");
self.currentRadian = [self radiansToDegreesFromPointX:currentPosition ToPointY:CGPointMake(0, 0) ToCenter:CGPointMake(105, 300)];
[CATransaction begin];
[CATransaction setDisableActions:YES];
_needleLayer.transform = CATransform3DMakeRotation(self.currentRadian, 0, 0, 1);
[CATransaction commit];
}
else if (gesture.state == UIGestureRecognizerStateEnded)
{
}
}
#pragma mark - 计算触点和中心点的弧度
-(float)radiansToDegreesFromPointX:(CGPoint)start ToPointY:(CGPoint)end ToCenter:(CGPoint)center{
CGFloat x_space = start.x - center.x;
CGFloat y_space = center.y - start.y;
CGFloat r_space = sqrt(x_space*x_space + y_space*y_space);
CGFloat result = acos(x_space/r_space);
if (start.x>=center.x&&start.y<=center.y) {
result = M_PI_2-result;
}
if (start.x>=center.x&&start.y>center.y) {
result = M_PI_2 + result;
}
NSLog(@"=====%f",result);
if (start.x<center.x&&start.y>=center.y) {
result = M_PI_2 + result;
}
if (start.x<center.x&&start.y<=center.y) {
result = M_PI_2-result;
}
return result;
}
#pragma mark - 计算触点到中心点的距离
-(float)distanceFromPointX:(CGPoint)start distanceToPointY:(CGPoint)end{
float distance;
CGFloat xDist = (end.x - start.x);
CGFloat yDist = (end.y - start.y);
distance = sqrt((xDist * xDist) + (yDist * yDist));
return distance;
}