Search code examples
iosswiftuibuttonhittest

Custom shape touchable area


I have a shape like below and I want set it as background to my UIButton but touchable area is a rectangle, any suggestion to change touchable area to shape boarders?

enter image description here


Solution

  • Actually I found it on this like and working perfectly:

    How to know that if the only visible area of a .png is touched in XCode (swift or objective C)

    But must change code like below:

       func alphaFromPoint(point: CGPoint) -> CGFloat {
       var pixel: [UInt8] = [0, 0, 0, 0]
       let colorSpace = CGColorSpaceCreateDeviceRGB();
       let alphaInfo : CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
       let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, alphaInfo.rawValue) //need add .rawValue to alphaInfo
    
       CGContextTranslateCTM(context, -point.x, -point.y);
    
       self.layer.renderInContext(context!)
    
       let floatAlpha = CGFloat(pixel[3])
       return floatAlpha
    

    }