ios - 访问drawRect外部的CGContext来识别饼图上的触摸事件并识别触摸的 block

标签 ios swift core-graphics drawrect cgcontext

我正在实现一个自定义 UIControl,它看起来像一个包含 n 个部分的饼图: n = 6

因此,我继承了 UIControl 并覆盖了它的 drawRect: 方法。在那里,我正在使用 CGContextAddArc 绘制 n 个片段。因此,我将根据需要绘制的部分进行循环,然后相应地设置 startAngleendAngle

现在,对于与控件的交互,从触摸事件中识别哪些被触摸对我来说很重要。我的方法是使用 CGContextPathContainsPoint。但是我需要在 drawRect: 之外调用它,所以 CGContext 不可用。

func indexOfTrackForPoint(point: CGPoint) -> Int
{
    // Configure parameters
    let basicTrackAngle = CGFloat(360 / tracks.count)
    let strokeWidth = 60.0
    let radius = CGFloat((CGFloat(self.frame.size.width) - CGFloat(strokeWidth)) / 2) - CGFloat(margin)

    // Initialize the context
    var context = UIGraphicsGetCurrentContext()
    CGContextSetLineWidth(context, CGFloat(strokeWidth))
    CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)

    for  i in 0...tracks.count-1 {

        // Start and end angles of current track
        var currentTrackStartAngle = CGFloat(i) * basicTrackAngle
        var currentTrackEndAngle = currentTrackStartAngle + basicTrackAngle

        CGContextAddArc(context, center.x, center.y, CGFloat(radius), toNormalizedRadian(currentTrackStartAngle), toNormalizedRadian(currentTrackEndAngle), 0)

        if pointOnPath(point, inContext: context){
            println("point found on track: \(i)")
            return i
        }

        CGContextDrawPath(context, kCGPathStroke) // or kCGPathFillStroke to fill and stroke the circle
    }
}

有谁知道如何实现这一点?是否可以在 drawRect: 之外获取 CGContext?

最佳答案

您可以在drawRect 实现中存储一组UIBezierPath 对象。然后,您可以稍后使用 UIBezierPath 实例方法 containsPoint:

轻松地对它们进行 HitTest

关于ios - 访问drawRect外部的CGContext来识别饼图上的触摸事件并识别触摸的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348335/

相关文章:

ios - iPhone 应用程序启动时多久可以调用 session didReceiveApplicationContext

ios - UIGraphicsGetCurrentContext 与 UIGraphicsBeginImageContext/UIGraphicsEndImageContext

javascript - IOS/Android 如何处理触摸事件

ios - 缩放使用 SKSpriteNodes 制作的钟摆

ios - 获取文档文件夹中的文件列表

ios - 为什么 CGContextSetShadowWithColor 也改变了当前的填充颜色?

swift - MacOS Quartz Event Tap 监听错误事件

iOS图标构建错误

android - 移动服务器应用聊天 REST API

ios - 检索多个解析图像(Swift)