Как вернуть CGImageRef из CGWindowListCreateImage в C#? - PullRequest
0 голосов
/ 17 февраля 2020

Я сейчас пытаюсь написать плагин для macOS для Unity. Я делаю скриншот рабочего стола с CGWindowListCreateImage . Я пытаюсь выяснить, как вернуть данные byte[] в C#, чтобы я мог создать Texture2D из них. Любая помощь будет принята с благодарностью, спасибо.

Она не хочет, чтобы я возвращал NSArray* Файл .h находится внизу.

NSArray* getScreenshot()
{
    CGImageRef screenShot = CGWindowListCreateImage( CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);

    return getRGBAsFromImage(screenShot);
}

NSArray* getRGBAsFromImage(CGImageRef imageRef)
{
    // First get the image into your data buffer
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    NSUInteger bytesPerPixel = 4;
    unsigned long count = width * height * bytesPerPixel;

    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) alloca(height * width * 4);

    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                    bitsPerComponent, bytesPerRow, colorSpace,
                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int x = 0, y = 0;
    NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;

    for (int i = 0 ; i < count ; ++i)
    {
        CGFloat alpha = ((CGFloat) rawData[byteIndex + 3] ) / 255.0f;
        CGFloat red   = ((CGFloat) rawData[byteIndex]     ) / alpha;
        CGFloat green = ((CGFloat) rawData[byteIndex + 1] ) / alpha;
        CGFloat blue  = ((CGFloat) rawData[byteIndex + 2] ) / alpha;
        byteIndex += bytesPerPixel;

        NSColor *acolor = [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result insertObject:acolor atIndex:count];

    }

  free(rawData);

  return result;
}


#ifndef TestMethods_hpp
#define TestMethods_hpp
#import <Foundation/Foundation.h>
#include <Carbon/Carbon.h>
#include <stdio.h>
#include <AppKit/AppKit.h>
typedef void (*Unity_Callback1)(char * message);

extern "C" {
    NSArray* getScreenshot();
}
#endif /* TestMethods_h */
...