Skip to content

Instantly share code, notes, and snippets.

@touyou
Created February 20, 2018 15:17
Show Gist options
  • Save touyou/f709a96fa046f45165e120ed3bc644b6 to your computer and use it in GitHub Desktop.
Save touyou/f709a96fa046f45165e120ed3bc644b6 to your computer and use it in GitHub Desktop.
import UIKit
class ImageButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.imageView?.image?.getAlpha(point) == 0 {
return nil
} else {
return super.hitTest(point, with: event)
}
}
}
extension UIImage {
func getAlpha(_ pos: CGPoint) -> CGFloat {
let imageData = self.cgImage?.dataProvider?.data!
let data: UnsafePointer = CFDataGetBytePtr(imageData)
let address: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
return CGFloat(data[address + 3])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment