非常简单的问题...我有一个像素数组,如何在屏幕上显示它们?
#define WIDTH 10
#define HEIGHT 10
#define SIZE WIDTH*HEIGHT
unsigned short pixels[SIZE];
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
pixels[j*HEIGHT + i] = 0xFFFF;
}
}
就是这样...现在我怎样才能在屏幕上显示它们?
最佳答案
- 创建一个新的“Cocoa 应用程序”(如果您不知道如何创建 Cocoa 应用程序,请访问 Cocoa Dev Center)
- 子类化 NSView(如果您不知道如何子类化 View read section "Create the NSView Subclass" )
- 在界面生成器上将 NSWindow 大小设置为 400x400
在您的 NSView 中使用此代码
#import "MyView.h" @implementation MyView #define WIDTH 400 #define HEIGHT 400 #define SIZE (WIDTH*HEIGHT) #define BYTES_PER_PIXEL 2 #define BITS_PER_COMPONENT 5 #define BITS_PER_PIXEL 16 - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code here. } return self; } - (void)drawRect:(NSRect)dirtyRect { // Get current context CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort]; // Colorspace RGB CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Pixel Matrix allocation unsigned short *pixels = calloc(SIZE, sizeof(unsigned short)); // Random pixels will give you a non-organized RAINBOW for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { pixels[i+ j*HEIGHT] = arc4random() % USHRT_MAX; } } // Provider CGDataProviderRef provider = CGDataProviderCreateWithData(nil, pixels, SIZE, nil); // CGImage CGImageRef image = CGImageCreate(WIDTH, HEIGHT, BITS_PER_COMPONENT, BITS_PER_PIXEL, BYTES_PER_PIXEL*WIDTH, colorSpace, kCGImageAlphaNoneSkipFirst, // xRRRRRGGGGGBBBBB - 16-bits, first bit is ignored! provider, nil, //No decode NO, //No interpolation kCGRenderingIntentDefault); // Default rendering // Draw CGContextDrawImage(context, self.bounds, image); // Once everything is written on screen we can release everything CGImageRelease(image); CGColorSpaceRelease(colorSpace); CGDataProviderRelease(provider); } @end
关于objective-c - 如何在 NSWindow 上显示像素数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10955913/