gpt4 book ai didi

ios - 仅使 png 可点击 UIbutton swift 的可见部分

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:04 24 4
gpt4 key购买 nike

您好,我有一个文件,其中 View 由 10 个分层图像组成,这些图像是带有大透明部分的 png。我喜欢它只能在可见部分上点击,但无论我如何尝试,它都只是注册点击的顶部图像/按钮。我尝试过使用 UIbuttons 和可点击的 UIImage View 。我在 swift 2.2 工作。有没有人知道如何解决这个问题?

最佳答案

  1. 在 View 层次结构中按 z 位置对 ImageView 进行排序。这确保了多个不透明区域重叠时的正确行为。
  2. 遍历所有图像。
  3. 对于每张图片,检查所选位置像素的 alpha 分量。
  4. alpha 将在某个范围内(通常在 0 ... 100 之间)。如果 alpha 大于某个阈值量,则响应点击并退出,否则检查下一张图像。

下面是一个如何工作的例子。图像和点击手势已添加到界面生成器中。此示例只是将点击 View 置于最前面,但可以根据您所需的行为轻松修改它。

class ClickViewController: UIViewController {

@IBOutlet var images: [UIImageView]!

@IBAction internal func tapGestureHandler(gesture: UITapGestureRecognizer) {

let sorted = images.sort() { a, b in
return a.layer.zPosition < b.layer.zPosition
}

for (i, image) in sorted.enumerate() {

let location = gesture.locationInView(image)
let alpha = image.alphaAtPoint(location)

if alpha > 50.0 {

print("selected image #\(i) \(image.layer.zPosition)")
view.addSubview(image)

return
}
}
}
}

这是一个如何设置 Storyboard的示例。注意 ImageView 和点击手势识别器。还可以通过编程方式添加 View 。

Views and gesture recogniser

将每个图像链接到 images IBCollection,在 Connections Inspector 中的 Referencing Outlet Collections 下。

Images added to the IBCollection

这里是确定图像中点击位置像素的 alpha 分量的代码。以下代码是对另一个 similar question on SO 的回答。 .

extension UIImageView {

//
// Return the alpha component of a pixel in the UIImageView.
//
// See: https://stackoverflow.com/questions/27923232/how-to-know-that-if-the-only-visible-area-of-a-png-is-touched-in-xcode-swift-o?rq=1
//
func alphaAtPoint(point: CGPoint) -> CGFloat {

var pixel: [UInt8] = [0, 0, 0, 0]
let colorSpace = CGColorSpaceCreateDeviceRGB();
let alphaInfo = CGImageAlphaInfo.PremultipliedLast.rawValue

guard let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, alphaInfo) else {
return 0
}

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

layer.renderInContext(context)

let floatAlpha = CGFloat(pixel[3])

return floatAlpha
}
}

参见 example app available on GitHub .

关于ios - 仅使 png 可点击 UIbutton swift 的可见部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38340052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com