通过CommandBuffer.IssuePluginCustomTextureUpdate(IntPtr callback, Texture targetTexture, uint userData);
我们可以在原生层更改 UnityTexture 的内容.
原生层的回调:
void TextureUpdateCallback(int eventID, void* data)
{
auto event = (UnityRenderingExtEventType)eventID;
auto params = (UnityRenderingExtTextureUpdateParamsV2*)data;
}
eventID :UnityRenderingExtEventType 中的下面两个 是更新Texture内容相关的
-
kUnityRenderingExtEventUpdateTextureBegin
该事件在更新texture内容之前触发,我们可以这时通过 *data 来更改贴图内容。if (event == kUnityRenderingExtEventUpdateTextureBeginV2) { uint8_t* img = new uint32_t[params->width * params->height * 4]; // Set image data here. params->texData = img; }
-
kUnityRenderingExtEventUpdateTextureEnd,
该事件在texture内容更新之后触发,我们可以在这里释放资源。if (event == kUnityRenderingExtEventUpdateTextureEndV2) { delete[] reinterpret_cast<uint32_t*>(params->texData); }
通过下面函数让Unity调用:
extern "C"
UnityRenderingEventAndData UNITY_INTERFACE_EXPORT
GetTextureUpdateCallback()
{
return TextureUpdateCallback;
}
以上是原生层相关代码。下面是Unity部分的代码
[DllImport("DllName")] static extern IntPtr GetTextureUpdateCallback();
var callback = GetTextureUpdateCallback();
m_CommandBuffer.IssuePluginCustomTextureUpdateV2(callback,
texture, userData);
Graphics.ExecuteCommandBuffer(m_CommandBuffer);
可以参考这里 :https://github.com/keijiro/TextureUpdateExample
我自己在此基础上加入了原生层加载一张图片并设置为Texture内容,代码放到了这里https://code.aliyun.com/shppniu/nativetexture.git,1秒后显示原生加载的图片内容,效果如下:
加载图片
[UIImage imageNamed:@"test.png"]]
xcode.png
UIImage转为 Raw Image 读取像素数据
CGImageRef inputCGImage = [image CGImage];
NSUInteger width = CGImageGetWidth(inputCGImage);
NSUInteger height = CGImageGetHeight(inputCGImage);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
// UInt32 * pixels;
self.pixels = (uint32_t *) calloc(height * width, sizeof(UInt32));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(self.pixels, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), inputCGImage);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
更新Texture内容:
void TextureUpdateCallback(int eventID, void* data)
{
auto event = static_cast<UnityRenderingExtEventType>(eventID);
if (event == kUnityRenderingExtEventUpdateTextureBegin)
{
// UpdateTextureBegin: Generate and return texture image data.
auto params = reinterpret_cast<UnityRenderingExtTextureUpdateParams*>(data);
auto frame = params->userData;
params->texData = PPImgProcesser.sharedInstance.pixels;
}
else if (event == kUnityRenderingExtEventUpdateTextureEnd)
{
// UpdateTextureEnd: Free up the temporary memory.
auto params = reinterpret_cast<UnityRenderingExtTextureUpdateParams*>(data);
//delete[] reinterpret_cast<uint32_t*>(params->texData);
}
}
网友评论