Guest User

Untitled

a guest
Oct 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. func hitTest(_ point: CGPoint,
  2. withEvent event: UIEvent?) -> UIView? // that's for handling the case of multiple custom subviews on your view rather than for evaluating if it's your view to handle the touch
  3.  
  4. func pointInside(_ point: CGPoint,
  5. withEvent event: UIEvent?) -> Bool // way more preferable than hit test in your case!!!
  6.  
  7. func alphaFromPoint(point: CGPoint) -> CGFloat {
  8. var pixel: [UInt8] = [0, 0, 0, 0]
  9. let colorSpace = CGColorSpaceCreateDeviceRGB();
  10. let alphaInfo : CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
  11. let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, alphaInfo.rawValue) //need add .rawValue to alphaInfo
  12.  
  13. CGContextTranslateCTM(context, -point.x, -point.y);
  14.  
  15. self.layer.renderInContext(context!)
  16.  
  17. let floatAlpha = CGFloat(pixel[3])
  18. return floatAlpha
  19.  
  20. extension UIButton{
  21.  
  22. open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  23. if let touch = event!.touches(for: self)?.first {
  24. let location = touch.location(in: self)
  25. if alphaFromPoint(point: location) == 0 {
  26. self.cancelTracking(with: nil)
  27. print("cancelled!")
  28. } else{
  29. super.touchesBegan(touches, with: event)
  30. }
  31. }
  32. }
  33.  
  34. func alphaFromPoint(point: CGPoint) -> CGFloat {
  35. var pixel: [UInt8] = [0, 0, 0, 0]
  36. let colorSpace = CGColorSpaceCreateDeviceRGB();
  37. let alphaInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  38. let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: alphaInfo.rawValue)
  39.  
  40. context!.translateBy(x: -point.x, y: -point.y)
  41. self.layer.render(in: context!)
  42.  
  43. let floatAlpha = CGFloat(pixel[3])
  44. return floatAlpha
  45. }
  46. }
Add Comment
Please, Sign In to add comment