gpt4 book ai didi

objective-c - Mac 操作系统 cocoa : Draw a simple pixel on a canvas

转载 作者:太空狗 更新时间:2023-10-30 03:23:57 28 4
gpt4 key购买 nike

我希望我能找到这个问题的答案。我找了又找,找不到正确的答案。这是我的情况:

在 Mac OS Cocoa 应用程序中,我想在应用程序窗口的专用区域上绘制一个像素(实际上是几个像素)。我认为,将 NSImageView 放在那里会更好(我使用 IB 这样做并将 socket 连接到我的应用程序委托(delegate))并在其上绘制而不是我的 NSWindow .

我到底该怎么做? Mac OS 似乎提供 NSBezierPath 作为最基本的绘图工具——是这样吗?这让我非常震惊。我有悠久的 Windows 编程经验,通常在 Canvas 上绘制像素是最简单的事情。

我不想使用 OpenGL,我不确定 Quartz 在多大程度上参与其中。

我想要的只是一些关于如何在真正的 Objective-C/Cocoa 中实现这个伪代码的帮助:

imageObj.drawPixel(10,10,blackColor);

我很想听听您对此的回答,我相信这会对很多开始使用 Cocoa 的人有所帮助。

谢谢!

最佳答案

您要求的是以下两种方法之一:

NSBitmapRep setColor:atX:y:更改指定坐标处像素的颜色。

NSBitmapRep setPixel:atX:y:将指定坐标处的接收器像素设置为指定的原始像素值。

请注意,这些在 iOS 上不可用。在 iOS 上,执行此操作的方法似乎是为给定的色彩空间(可能是 RGB)创建像素数据的原始缓冲区,用颜色数据填充它(编写一个小的 setPixel 方法来执行此操作)然后调用 CGImageCreate()像这样:

    //Create a raw buffer to hold pixel data which we will fill algorithmically
NSInteger width = theWidthYouWant;
NSInteger height = theHeightYouWant;
NSInteger dataLength = width * height * 4;
UInt8 *data = (UInt8*)malloc(dataLength * sizeof(UInt8));

//Fill pixel buffer with color data
for (int j=0; j<height; j++) {
for (int i=0; i<width; i++) {

//Here I'm just filling every pixel with red
float red = 1.0f;
float green = 0.0f;
float blue = 0.0f;
float alpha = 1.0f;

int index = 4*(i+j*width);
data[index] =255*red;
data[++index]=255*green;
data[++index]=255*blue;
data[++index]=255*alpha;

}
}

// Create a CGImage with the pixel data
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef image = CGImageCreate(width, height, 8, 32, width * 4, colorspace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,

provider, NULL, true, kCGRenderingIntentDefault);

//Clean up
CGColorSpaceRelease(colorspace);
CGDataProviderRelease(provider);
// Don't forget to free(data) when you are done with the CGImage

最后,您可能想要操作已加载到 CGImage 中的图像中的像素。在标题为 QA1509 Getting the pixel data from a CGImage object 的 Apple 技术问答中有用于执行此操作的示例代码.

关于objective-c - Mac 操作系统 cocoa : Draw a simple pixel on a canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4356441/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com