首页 > 解决方案 > 用于更新 SKMutableTexture 的 Objective C 语法

问题描述

我有一些很棒的代码来处理 a 中的像素skmutabletexture,但它是在 Swift 中,我还没有进入。

其中 90% 我可以翻译成 Objective C 但不能创建rgbaPtrand rgbaBufferPtrstruct有没有一种等效的方法可以使用Objective C中的格式对这些进行排序?或者这种方法是 Swift 特有的?

我的代码(在 Swift 中):

struct RGBA {
    let r: UInt8
    let g: UInt8
    let b: UInt8
    let a: UInt8
}

 texture.modifyPixelData { (pixelData, lengthInBytes) in
            // Assume that the memory of the mutable texture is bound to a tightly packed 4 element UInt32 struct.
            let rgbaPtr = pixelData?.assumingMemoryBound(to: RGBA.self)
            
            // Calculate the number of texture elements in the texture based on the byte count.
            let pixelCount = Int(lengthInBytes / MemoryLayout<RGBA>.stride)
            
            // Create a buffer pointer to more conveniently mutate the texture data.
            let rgbaBufferPtr = UnsafeMutableBufferPointer(start: rgbaPtr, count: pixelCount)
            
            // Iterate through the pixels and update them individually.
            for index in 0..pixelCount {
                
                // Calculate the row and column in the pixel (origin is bottom left corner)
                let row = index / width
                let column = index % width
                
                if row > 10 && column > 10 {
                    let myColor = RGBA(r: 0, g: 0, b: 0, a: 1)
                    
                    // Assign the color to the pixel.
                    rgbaBufferPtr[index] = myColor
                }
            }
        }

标签: iosobjective-cswiftxcodesprite-kit

解决方案


也许像这样 - 一个非常快的,你需要完成...。

你看到的是 Swift 处理指针的方式,这对于 Objective-C 来说是很自然的,所以它实际上更直接。

struct RGBA
{
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    uint8_t alpha;
};

void modifyPixedData ( struct RGBA * pixelData, NSUInteger lengthInBytes )
{
    // Now you can just use it
    struct RGBA myColor;

    myColor.red   = ...;
    myColor.green = ...;
    myColor.blue  = ...;
    myColor.alpha = ...;

    NSUInteger width = ...;
    NSUInteger pixelCount = lengthInBytes / sizeof ( struct RGBA );

    for ( NSUInteger index = 0; index < pixelCount; index ++ )
    {
        // Calculate the row and column in the pixel (origin is bottom left corner)
        NSUInteger row = index / width;
        NSUInteger column = index % width;

        if ( row > 10 && column > 10 )
        {
            * ( pixelData + index ) = myColor;
        }
    }
}

也有很多方法可以做到这一点,你也可以这样做

pixelData[ index ] = myColor;

或者你可以用一个指针循环它,这是非常自然和高效的,例如

    struct RGBA * end = pixelData + lengthInBytes;

    NSUInteger row    = 0;
    NSUInteger column = 0;

    while ( pixelData < end )
    {
        if ( row > 10 && column > 10 )
        {
            * pixelData = myColor;
        }

        pixelData ++;
        row ++;

        if ( row == width )
        {
            row = 0;
            column ++;
        }

    }

推荐阅读