在SKScene快捷方式中获取点的颜色 [英] Get Color of point in a SKScene swift
问题描述
我需要在Swift中为我的游戏获取像素/点的颜色.所以我试图找到一个输入CGPoint并返回Color的函数,到目前为止我发现的所有东西都只返回了(0,0,0,0).我认为这是因为我是在我的游戏场景类(这是一个SKScene)中执行此操作的,而该场景仅由视图控制器加载.有解决方案吗?
I need to get the color of a pixel/point for my game in Swift. So I tried to find a function that inputs a CGPoint and returns a Color, everything that I have found so far has only returned (0,0,0,0). I think that this is because I am doing this in my game scene class(which is an SKScene), and the scene is only being loaded by a view controller. Any Solutions?
(如果有更好的方法可以检查精灵是否触摸到也可以工作的颜色)
(If there is a better way to check if a sprite is touching a color that would work as well)
谢谢.
推荐答案
添加以下方法:
extension UIView {
func getColor(at point: CGPoint) -> UIColor{
let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
context.translateBy(x: -point.x, y: -point.y)
self.layer.render(in: context)
let color = UIColor(red: CGFloat(pixel[0]) / 255.0,
green: CGFloat(pixel[1]) / 255.0,
blue: CGFloat(pixel[2]) / 255.0,
alpha: CGFloat(pixel[3]) / 255.0)
pixel.deallocate(capacity: 4)
return color
}
}
您可以通过它获取想要的点的颜色
You can get the color of the point you want with
let color = someView.getColor(at: somePoint)
这篇关于在SKScene快捷方式中获取点的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!