如何在触摸时获得像素颜色(Swift)?

时间:2015-04-22 07:20:46

标签: ios swift cashapelayer

我有各种CAShapeLayers,每个都有独特的颜色,如下所示:

    shape1.strokeColor = UIColor(red: 85/255.0, green: 176/255.0, blue: 112/255.0, alpha: 1.0).
    shape2.strokeColor = UIColor(red: 222/255.0, green: 171/255.0, blue: 66/255.0, alpha: 1.0).CGColor

使用touchesBegan函数,我想确定是否已点击CAShapeLayer以及它是哪一个,以便进行合适的操作。我知道可以使用hitTestCGPathContainsPoint,但我想使用不同的方法。如何比较点击的点的颜色与CAShapeLayers的颜色?

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

此方法应该用于找出触摸点的像素颜色:

func colorAtPoint(point:CGPoint) -> UIColor
{
    var pixels = UnsafeMutablePointer<CUnsignedChar>.alloc(4)

    var colorSpace = CGColorSpaceCreateDeviceRGB()
    var bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
    var context = CGBitmapContextCreate(pixels, 1, 1, 8, 4, colorSpace, bitmapInfo)

    CGContextTranslateCTM(context, -point.x, -point.y)

    shapeLayer.renderInContext(context)


    var color:UIColor = UIColor(red: CGFloat(pixels[0])/255.0, green: CGFloat(pixels[1])/255.0, blue: CGFloat(pixels[2])/255.0, alpha: CGFloat(pixels[3])/255.0)

    pixels.dealloc(4)

    return color
}