gpt4 book ai didi

ios - 什么是 UnsafeMutablePointer?如何修改底层内存?

转载 作者:IT王子 更新时间:2023-10-29 05:40:38 26 4
gpt4 key购买 nike

我正在尝试使用 SpriteKit 的 SKMutableTexture 类,但我不知道如何使用 UnsafeMutablePointer< Void > .我有一个模糊的想法,它是指向内存中一连串字节数据的指针。但是我该如何更新呢?这在代码中实际上是什么样的?

编辑

这是一个可以使用的基本代码示例。我如何让它做一些像在屏幕上创建一个红色方 block 这样简单的事情?

    let tex = SKMutableTexture(size: CGSize(width: 10, height: 10))
tex.modifyPixelDataWithBlock { (ptr:UnsafeMutablePointer<Void>, n:UInt) -> Void in

/* ??? */

}

最佳答案

来自 SKMutableTexture.modifyPixelDataWithBlock 的文档:

The texture bytes are assumed to be stored as tightly packed 32 bpp, 8bpc (unsigned integer) RGBA pixel data. The color components you provide should have already been multiplied by the alpha value.

因此,当您获得 void* 时,底层数据采用 4x8 位流的形式。

您可以像这样操纵这样的结构:

// struct of 4 bytes
struct RGBA {
var r: UInt8
var g: UInt8
var b: UInt8
var a: UInt8
}

let tex = SKMutableTexture(size: CGSize(width: 10, height: 10))
tex.modifyPixelDataWithBlock { voidptr, len in
// convert the void pointer into a pointer to your struct
let rgbaptr = UnsafeMutablePointer<RGBA>(voidptr)

// next, create a collection-like structure from that pointer
// (this second part isn’t necessary but can be nicer to work with)
// note the length you supply to create the buffer is the number of
// RGBA structs, so you need to convert the supplied length accordingly...
let pixels = UnsafeMutableBufferPointer(start: rgbaptr, count: Int(len / sizeof(RGBA))

// now, you can manipulate the pixels buffer like any other mutable collection type
for i in indices(pixels) {
pixels[i].r = 0x00
pixels[i].g = 0xff
pixels[i].b = 0x00
pixels[i].a = 0x20
}
}

关于ios - 什么是 UnsafeMutablePointer<Void>?如何修改底层内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28398677/

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