ios - 用于更新 SKMutableTexture 的 Objective C 语法
问题描述
我有一些很棒的代码来处理 a 中的像素skmutabletexture
,但它是在 Swift 中,我还没有进入。
其中 90% 我可以翻译成 Objective C 但不能创建rgbaPtr
and rgbaBufferPtr
。struct
有没有一种等效的方法可以使用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
}
}
}
解决方案
也许像这样 - 一个非常快的,你需要完成...。
你看到的是 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 ++;
}
}
推荐阅读
- firebase - 将 Firebase 崩溃报告更新到 Firebase Crashlytics:仍在旧仪表板上
- python - Airflow/Composer - 在 zip 打包的 DAG 中找不到模板
- php - MySQL 错误“未选择数据库”是什么意思?
- php - SagePay API - 创建交易时请求格式不正确 - Php
- mysql - 如何通过控制台禁用对数据库导入的外键检查?
- android - Android:如何在 RecyclerView 中为每张卡片设置不同的高度?
- string - 检查 Map 中的值是否是 String 的一部分
- git - 如何在“git push -u”中自动使用本地分支名称
" - sql - Bigquery - 使用数据集在 UI 上执行查询
- c# - SignalR 并在没有身份验证的情况下获取用户 ID