如何从Given UIView旋转某个CGPoint。
以下图片定义了一个CAShapeLayer,其中有四个UIView作为顶部,左侧,底部和右侧:
我已将UIRotationGesture添加到self.view中,我通过它旋转CAShapeLayer,所以我想移动它的点以及CAShapeLayer,如下图所示:
以下定义了我用来实现相同但却遇到一些问题的代码:
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer
{
if(recognizer.state == UIGestureRecognizerStateBegan)
{
CGPoint touch1 = [recognizer locationOfTouch:0 inView:_imgBackground];
CGPoint touch2 = [recognizer locationOfTouch:1 inView:_imgBackground];
UIBezierPath *bezierpath = [UIBezierPath bezierPath];
bezierpath.CGPath = shapeLayer.path;
}
else if(recognizer.state == UIGestureRecognizerStateChanged)
{
CGPathRef path = createPathRotatedAroundBoundingBoxCenter(shapeLayer.path, rotationGesture.rotation);
shapeLayer.path = path;
CGPathRelease(path);
rotationGesture.rotation = 0;
}
else if (recognizer.state == UIGestureRecognizerStateEnded)
{
NSMutableArray *rotatingLayerPoints = [NSMutableArray array]; // will contain all the points of object that is been rotated
CGPathApply(shapeLayer.path, (__bridge void * _Nullable)(rotatingLayerPoints), CGPathApplier);
degreeOfRotation = DEGREES_TO_RADIANS([self getDegreeFromStartPoint:[[rotatingLayerPoints objectAtIndex:0] CGPointValue] endPoint:[[rotatingLayerPoints objectAtIndex:1] CGPointValue]]); // getting degree of first line's movement
CGRect frame = CGPathGetBoundingBox(shapeLayer.path);
CGPoint rotationPoint = CGPointMake(frame.origin.x + (frame.size.width/2), frame.origin.y + (frame.size.height/2));// The point we are rotating around
CGFloat minX = CGRectGetMinX(topPoint.frame);
CGFloat minY = CGRectGetMinY(topPoint.frame);
CGFloat width = CGRectGetWidth(topPoint.frame);
CGFloat height = CGRectGetHeight(topPoint.frame);
CGPoint anchorPoint = CGPointMake((rotationPoint.x-minX)/width,
(rotationPoint.y-minY)/height);
topPoint.layer.anchorPoint = anchorPoint;
topPoint.layer.position = rotationPoint;
topPoint.transform = CGAffineTransformMakeRotation(degreeOfRotation);
}
}
void CGPathApplier (void *info, const CGPathElement *element) // used to get points from CGPath
{
NSMutableArray *bezierPoints = (__bridge NSMutableArray *)info;
CGPoint *points = element->points;
CGPathElementType type = element->type;
switch(type)
{
case kCGPathElementMoveToPoint: // contains 1 point
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
break;
case kCGPathElementAddLineToPoint: // contains 1 point
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
break;
case kCGPathElementAddQuadCurveToPoint: // contains 2 points
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
break;
case kCGPathElementAddCurveToPoint: // contains 3 points
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[2]]];
break;
case kCGPathElementCloseSubpath: // contains no point
break;
}
}