我试图在自定义UIView
中使用自定义CALayer
实现UI元素。检测旋转CAShapeLayer上的接触
基本上,用户用他/她的手指围绕一个圆移动滑块,所以我有一个用于交互的层,然后是表示滑块本身的CAShapeLayer
类型的子层。我认为在圆周上移动滑块最简单的方法就是围绕它的z轴旋转CAShapeLayer
。
尽管滑块在视觉上按预期旋转,但是当我对接收的触摸执行命中测试时,“可击中”区域仍驻留在滑块的预旋转位置。就好像CAShapeLayer
的旋转的视觉效果与嵌入在图层内部的UIBezierPath
解耦以形成图层的path
属性,因为我正在使用该路径与CGPathContainsPoint()
一起识别滑块上的触摸。
我是新来的核心图形一般,所以我想可能有一个属性,我没有在这里设置正确,但我努力弄清楚它是什么。
下面是代码:
TouchableLayer.m
@interface TouchableLayer()
{
CAShapeLayer *_slider; // The interactive slider that gets moved around the circle.
}
-(id) initWithPosition:(NSInteger) position // Designated initializer for this layer.
{
if (self = [super init])
{
_slider = [CAShapeLayer layer];
_slider.fillColor = [UIColor blackColor].CGColor;
[self addSublayer:_slider];
}
return self;
}
-(void) setFrame:(CGRect)frame
{
[super setFrame:frame];
_slider.frame = frame;
// This path is currently hardcoded to be in the right starting spot according to
// other UI elements, but the magic numbers will go away once I figure out this
// rotation issue.
_slider.path = [UIBezierPath bezierPathWithRect:CGRectMake(self.bounds.size.width-47, self.bounds.size.height/2-5, 30.0f, 10.0f)].CGPath;
}
// Checks if the given touch location was on the slider. Returns YES if it was and NO if it was not.
-(BOOL) checkSliderTouchAtPoint: (CGPoint) point
{
if (CGPathContainsPoint(_slider.path , NULL, point, NO))
{
return YES;
}
else
{
return NO;
}
}
// Purpose: Takes the given touch location, determines the angle (in radians) that it forms with respect the center of the screen,
// and returns that angle on the interval [0-2pi] radians. [0-2pi] radians follows a positive counterclockwise path.
-(double) angleForTouchPoint:(CGPoint) point
{
// We use the positive counterclockwise coordinate system in the drawing code since that's what's used traditionally
// outside of Apple's APIs, so multiplying the result of
// atan2() by -1 converts the angle from a positive clockwise unit circle to a positive counterclockwise
// unit circle.
double angleInRadians = -1*atan2(point.y - (self.frame.size.height/2), point.x - self.frame.size.width/2);
if (angleInRadians < 0) // Convert angle to 0 - 2pi radians; we want non-negative angles.
{
angleInRadians += M_PI*2;
}
return angleInRadians;
}
// points get fed into this from the UIView.
-(void) updateWithTouchAtPoint:(CGPoint) point
{
if ([self checkSliderTouchAtPoint:point])
{
double touchAngle = [self angleForTouchPoint:point];
_slider.transform = CATransform3DMakeRotation(-M_PI, 0.0, 0.0, 1.0); // Hardcoded angle rotation for now since I need to do some subtraction later in order to determine the amount to rotate based on touches.
}
}
我真的很感激任何帮助,您可以提供!
感谢您的答复,它看起来像你的解决方案工作。我现在唯一的问题仍然是,它看起来不再围绕屏幕中心旋转整个图层,而是将图形旋转到位,而不会沿着圆圈移动。有没有一个锚点或我可以设置的东西,以便沿着圆形路径旋转滑块,而无需为每次触摸手动翻译它? –
实际上,事实证明,我添加了一些处理setFrame方法中的边界/ etc的代码,并导致它不像我最初发布时那样旋转。没关系! –
伟大! +1。 – Unheilig