【问题标题】:Find the direction UISlider is pointing找到 UISlider 指向的方向
【发布时间】:2012-06-12 11:14:42
【问题描述】:

我有一个包含自定义UISliderUIView 类。当这个 UIView 添加到 viewController 时,它会随机旋转使用

newSlider.transform = CGAffineTransformRotate(newSlider.transform, degreesToRadians(random));

现在我想要做的是动画UISlider 拇指图像飞离滑块的末端。 我面临的问题是获取滑块开始/结束的坐标,以便我可以计算出拇指图像的移动方式。

我曾尝试使用trackRectForBounds,但无论UIView 应用的旋转如何,它都会给我完全相同的坐标

我已经在我的UIView 课程中尝试过这些:

CGRect trackRect = [customSlider trackRectForBounds:customSlider.bounds];

CGRect trackRect2 = [customSlider trackRectForBounds:self.window.bounds];

无论旋转如何,它都会给我 {{2, 1}, {288, 50}} 和 {{2, 215}, {316, 50}}。我认为它给了我来自UIView 而不是屏幕的矩形。

【问题讨论】:

  • 为什么先是newSlider,然后是customSlider
  • newSlider 在我的 ViewController 中。它基本上是整个 UIView 类。 MyCustomSliderView *newSlider customSlider 在该 UIView 类中,指的是添加到 UIView 中的 UISlider。
  • 无论矩形如何旋转,您都会得到它的原点和大小 - 边界或框架中不包含旋转信息。

标签: ios xcode cocoa-touch uiview uislider


【解决方案1】:

获取滑块的端点可以这样完成:

CGFloat rotation = [[newSlider.layer valueForKeyPath:@"transform.rotation.z"] floatValue];

CGFloat halfWidth = newSlider.bounds.size.width/2;
CGPoint sliderCenter = newSlider.center;
sliderCenter.y += newSlider.bounds.size.height/2; //this shouldn't be needed but it seems it is

CGFloat x1 = sliderCenter.x - halfWidth * cos(rotation);
CGFloat x2 = sliderCenter.x + halfWidth * cos(rotation);

CGFloat y1 = sliderCenter.y - halfWidth * sin(rotation);
CGFloat y2 = sliderCenter.y + halfWidth * sin(rotation);

CGPoint T1 = CGPointMake(x1, y1);
CGPoint T2 = CGPointMake(x2, y2);

【讨论】:

  • 这会给我旋转,但我需要的是矩形。我可以大致找出它指向的方向,所以如果它指向上和右,我需要底部/左侧坐标和顶部/右侧坐标,这样我就可以沿着两者之间的路径继续前进。
  • 你必须知道 rect 总是用 (x,y)(w,h) 定义而不是用 (x1,y1)(x2,y2)(x3,y3)(x4,y4 )。所以rect总是被认为是水平对齐的。您可以使用 rect(x,y) 的原点和方向来找出您需要的内容。
  • 我迷路了。如果我使用 NSLog(@"frame:%@",NSStringFromCGRect(self.frame)); 检查 UIView 框架它随着旋转而变大,但滑块并不总是从一个角落跑到另一个角落,因为视图也有背景图像。
  • 是的。框架更大,因为它包含旋转的视图。框架总是被认为是正交的(即:宽度是水平的,高度是垂直的)。实际上,如果将视图旋转 90°,宽度将变为高度,高度将变为宽度。
  • 好的我明白了,所以我可以得到轨道的矩形,就好像它水平和旋转一样,但是这些如何根据屏幕坐标给我轨道的起点/终点而不是旋转的视图坐标?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 2012-02-22
  • 1970-01-01
  • 2013-04-07
相关资源
最近更新 更多