草庐IT

ios - 在旋转的 CAShapeLayer 上检测触摸

coder 2024-01-17 原文

我正在尝试在自定义 UIView 中使用自定义 CALayer 来实现 UI 元素。

基本上,用户用他/她的手指围绕一个圆圈移动 slider ,所以我有一个交互层,然后是 CAShapeLayer 类型的子层,代表 slider 本身。我认为围绕圆圈移动 slider 的最简单方法是围绕其 z 轴旋转 CAShapeLayer

虽然 slider 确实按预期在视觉上旋转,但当我对接收到的触摸执行 HitTest 时,“可命中”区域仍然位于 slider 旋转前的位置。就好像 CAShapeLayer 的旋转视觉效果与嵌入层内的 UIBezierPath 解耦,形成 path 属性层,因为我将该路径与 CGPathContainsPoint() 结合使用以识别 slider 上的触摸。

一般来说,我是 Core Graphics 的新手,所以我想可能有一个属性我没有在这里正确设置,但我正在努力弄清楚它是什么。

代码如下:

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.
    }
}

非常感谢您提供的任何帮助!

最佳答案

我通常希望事件位置以它们被传递到的 UIView 的形式表示。由于在 _slider 上有一个相对于其超层(即 UIView 的支持层)的转换,因此您要使用的任何几何值都需要转换为该引用系。简而言之,您需要将点显式转换为 _slider 的引用系。尝试这样的事情:

-(BOOL) checkSliderTouchAtPoint: (CGPoint) point
{
    CGPoint pointInSliderLayer = [_slider convertPoint: point fromLayer: self.layer];
    return CGPathContainsPoint(_slider.path , NULL, pointInSliderLayer, NO);
}

关于ios - 在旋转的 CAShapeLayer 上检测触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17679124/

有关ios - 在旋转的 CAShapeLayer 上检测触摸的更多相关文章

  1. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. 旋转矩阵的几何意义 - 2

    点向量坐标矩阵的几何意义介绍旋转矩阵的几何含义之前,先介绍一下点向量坐标矩阵的几何含义点:在一维空间下就是一个标量,如同一条直线上,以任意某一个位置为0点,以一定的尺度间隔为1,2,3...,相反方向为-1,-2,-3...;如此就形成了一维坐标系,这时候任何一个点都可以用一个数值表示,如点p1=5,即即从原点出发沿着x轴正方向移动5个尺度;点p2=-3,负方向移动3个尺度;     在一维坐标系上过原点做垂直于一维坐标系的直线,则形成了二维坐标系,此时描述一个点需要两个数值来表示点p3=(3,2),即从原点出发沿着x轴正方向移动3个尺度,在此基础上沿着y轴正方向移动两个尺度的位置就是点p3。

  5. Unity 3D 制作开关门动画,旋转门制作,推拉门制作,门把手动画制作 - 2

    Unity自动旋转动画1.开门需要门把手先动,门再动2.关门需要门先动,门把手再动3.中途播放过程中不可以再次进行操作觉得太复杂?查看我的文章开关门简易进阶版效果:如果这个门可以直接打开的话,就不需要放置"门把手"如果门把手还有钥匙需要旋转,那就可以把钥匙放在门把手的"门把手",理论上是可以无限套娃的可调整参数有:角度,反向,轴向,速度运行时点击Test进行测试自己写的代码比较垃圾,命名与结构比较拉,高手轻点喷,新手有类似的需求可以拿去做参考上代码usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;u

  6. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  7. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  8. ruby - 检测由 RSpec、Ruby 运行的代码 - 2

    我想知道我的代码是否在rspec下运行。这可能吗?原因是我正在加载一些错误记录器,这些记录器在测试期间会被故意错误(expect{x}.toraise_error)弄得乱七八糟。我查看了我的ENV变量,没有(明显的)测试环境变量的迹象。 最佳答案 在spec_helper.rb的开头添加:ENV['RACK_ENV']='test'现在您可以在代码中检查RACK_ENV是否经过测试。 关于ruby-检测由RSpec、Ruby运行的代码,我们在StackOverflow上找到一个类似的问题

  9. ruby - 使用 Ruby Daemons gem 检测停止 - 2

    我正在使用rubydaemongem。想知道如何向停止操作添加一些额外的步骤?希望我能检测到停止被调用,并向其添加一些额外的代码。任何人都知道我如何才能做到这一点? 最佳答案 查看守护程序gem代码,它似乎没有用于此目的的明显扩展点。但是,我想知道(在守护进程中)您是否可以捕获守护进程在发生“停止”时发送的KILL/TERM信号...?trap("TERM")do#executeyourextracodehereend或者你可以安装一个at_exit钩子(Hook):-at_exitdo#executeyourextracodehe

  10. ruby - Ruby 脚本如何检测到它正在 irb 中运行? - 2

    我有一个定义类的Ruby脚本。我希望脚本执行语句BoolParser.generate:file_base=>'bool_parser'仅当脚本作为可执行文件被调用时,而不是当它被irbrequire(或通过-r在命令行上传递)时。我可以用什么来包装上面的语句,以防止它在我的Ruby文件加载时执行? 最佳答案 条件$0==__FILE__...!/usr/bin/ruby1.8classBoolParserdefself.generate(args)p['BoolParser.generate',args]endendif$0==_

随机推荐