我正在实现一个自定义 UIControl
,它看起来像一个包含 n 个部分的饼图:
因此,我继承了 UIControl
并覆盖了它的 drawRect:
方法。在那里,我正在使用 CGContextAddArc
绘制 n 个片段。因此,我将根据需要绘制的部分进行循环,然后相应地设置 startAngle
和 endAngle
。
现在,对于与控件的交互,从触摸事件中识别哪些被触摸对我来说很重要。我的方法是使用 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:
关于ios - 访问drawRect外部的CGContext来识别饼图上的触摸事件并识别触摸的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348335/