gpt4 book ai didi

ios - 在 SKScene、iOS、Swift 中获取/设置像素颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:37 25 4
gpt4 key购买 nike

我正在尝试编写一个处理像素的 iOS 游戏。我发现我可以使用提到的方法获得像素颜色 here ,还有其他获取图像像素颜色的方法。但是我找不到任何关于在 SKScene 中获取像素颜色的信息。 As no answer for this question

我想这与在 UIView 中使用的方法非常相似,但我不熟悉 Swift 中的像素编码。这是我用来在 UIView 中获取像素颜色的方法:

  func getPixelColorAtPoint(point:CGPoint) -> UIColor{

let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo.rawValue)

CGContextTranslateCTM(context, -point.x, -point.y)
self.layer.renderInContext(context!)
let color:UIColor = 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.dealloc(4)
return color
}

我想我需要更改行 '''self.layer....'''。谁能帮我解决这个问题?

此外,我找不到任何有关如何直接在 UIView 或 SKScene 中设置像素颜色的信息。有什么想法吗?

顺便说一句:我尝试创建一个大小为 1 像素的 UIView/SKNode 类,然后将其添加到 UIView/SKScene 以便我可以直接设置颜色。这对于少量像素是可行的。但我正在处理很多人,可能有数百或数千人。这不是正确的做法,因为性能很差。

最佳答案

最近我尝试使用此扩展从 SKTexture 获取像素,这对我有用:

extension SKTexture {
func getPixelColorFromTexture(position: CGPoint) -> SKColor {
let view = SKView(frame: CGRectMake(0, 0, 1, 1))
let scene = SKScene(size: CGSize(width: 1, height: 1))
let sprite = SKSpriteNode(texture: self)
sprite.anchorPoint = CGPointZero
sprite.position = CGPoint(x: -floor(position.x), y: -floor(position.y))
scene.anchorPoint = CGPointZero
scene.addChild(sprite)
view.presentScene(scene)
var pixel: [UInt8] = [0, 0, 0, 0]
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), bitmapInfo)
UIGraphicsPushContext(context!)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
UIGraphicsPopContext()
return SKColor(red: CGFloat(pixel[0]) / 255.0, green: CGFloat(pixel[1]) / 255.0, blue: CGFloat(pixel[2]) / 255.0, alpha: CGFloat(pixel[3]) / 255.0)
}
}

关于ios - 在 SKScene、iOS、Swift 中获取/设置像素颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936036/

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