###前提・実現したいこと
最終的な目標としては、透明な部分には押された際の処理を実行しないような実装を行ないたいです。
そのためまずはUIButton
に対しhitTest
をオーバライドし、タップされたピクセルのアルファ値を取得しようとしています。
しかしその際にpointの位置がずれているのか、透過部分でもアルファ値が1だったり、タップする場所によってはクラッシュします。
Thread 1: EXC_BAD_ACCESS(code=1, address+0x1048cb12c)
こちらの原因がわからないのでご相談しました。
###クラッシュする際の情報
Width =Optional(800) Height=Optional(444) BitsPerPixel=Optional(16) BytesPerRow=Optional(1600) BitsPerComponent=Optional(8) AlphaInfo=Optional(1) BitmapInfo=Optional(1) scale=2.0 point=(277.5, 377.0)
###該当のソースコード
swift
1import UIKit 2 3class TransparentButton: UIButton { 4 5 override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { 6 let pixelDataByteSize = 4 7 8 if let image = self.imageView?.image { 9 let imageData = image.cgImage?.dataProvider?.data 10 let data = CFDataGetBytePtr(imageData) 11 let scale = UIScreen.main.scale 12 let address: Int = ((Int(image.size.width) * Int(point.y * scale)) + Int(point.x * scale)) * pixelDataByteSize 13 14 15 print("Width =(String(describing: image.cgImage?.width))") 16 print("Height=(String(describing: image.cgImage?.height))") 17 print("BitsPerPixel=(String(describing: image.cgImage?.bitsPerPixel))") 18 print("BytesPerRow=(String(describing: image.cgImage?.bytesPerRow))") 19 print("BitsPerComponent=(String(describing: image.cgImage?.bitsPerComponent))") 20 print("AlphaInfo=(String(describing: image.cgImage?.alphaInfo.rawValue))") 21 print("BitmapInfo=(String(describing: image.cgImage?.bitmapInfo.rawValue))") 22 print("scale=((self.imageView?.image?.scale)!)") 23 print("point=(point)") 24 25 26 27 let r = CGFloat((data?[address])!) //Thread 1: EXC_BAD_ACCESS(code=1, address+0x1048cb12c) 28 let g = CGFloat((data?[address + 1])!) 29 let b = CGFloat((data?[address + 2])!) 30 let a = CGFloat((data?[address + 3])!) / 255.0 31 32 print(r, g, b, a) 33 34 } 35 36 return nil 37 } 38 39}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。